﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using PMisuseAn.io;
using PMisuseAn.behaviour.model;

using System.Collections;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms.Integration;
using System.Windows.Threading;
using System.Windows.Interop;
using System.Timers;
using Microsoft.Msagl.Drawing;
using Microsoft.Msagl.GraphViewerGdi;
using Microsoft.Msagl.Splines;
using PMisuseAn.util;
using System.Collections.Specialized;
using System.Data;
using PMisuseAn.behaviour.adaptation;

namespace PMisuseAn
{
    /// <summary>
    /// Interaction logic for EmulationEnvironmentWindow.xaml
    /// </summary>
    public partial class EmulationEnvironmentWindow : Window
    {
        public List<string> agentNames;
        public Agent source_agent;
        public string sourceMachineStartState;
        public string sourceMachineEndState;
        public string source_agent_name;
        public List<string> agentNamesInGroup;
        
        public Graph agentsGraph;
        public Graph glee_fsm_graph;

        public GViewer fsm_viewer = new GViewer();
        public GViewer agents_viewer = new GViewer();

        private DispatcherTimer timer;
        public event EventHandler agentGraphChanged;

        string stateName_;
        bool loadingTriggers = false;
        bool isEventUpdate = false;
        bool isStateUpdate = false;
        bool isStateActionUpdate = false;
        bool isStateActionSelection = false;
        bool isStateSelection = false;
        bool isEventSelection = false;
        bool isTransitionSelection = false;
        bool isTransitionRootSelection = false;
        bool isStateRootSelection = false;
        bool isEventRootSelection = false;
        
        Event newEvent;
        State newState;
        Transition newStateTransition;
        PMisuseAn.behaviour.model.Action newAction;
        List<Event> allExisitngEvents;
        List<State> allExistingStates;
        List<Transition> allExistingStateTransitions;
        List<PMisuseAn.behaviour.model.Action> allExistingStateActions;

        List<Attribute> agentAttributes;
        //List<Attribute> functionalAttributes;
        List<Attribute> environmentalAttributes;
        TreeViewItem stateActionSelected_tv;

        static Context contextInstance;
        public static MisuseAnalyser misuseAnalyser; 
        public static VulnerabilityAnalyser aggregationMisuseAnalyser;
        //static List<Object> parameterisedContextInstances_;
        //static Dictionary<Dictionary<Agent, Agent>, ListDictionary> sendReceiveContextAgent;
        public static string sourceAgentName;

        List<Agent> allAgents;
        Agent sendAgent = null;
        Agent receiveAgent = null;
        Agent subjectAgent = null;
        State message_s = null;
        Transition message_t = null;

        List<string> groupFunctions = null;
        List<string> groupNames = null;

        int int_seq_no = 1;
        int int_seq_no_specific = 1;
        bool stopCall;

        int interactionSeqNo = 1;
        int seqTimeline = 0;

        public EmulationEnvironmentWindow()
        {
            InitializeComponent();
            this.Left = 20;
            this.Top = 25;
            
            agentIntnet_lab.Visibility = System.Windows.Visibility.Hidden;

            loadAllAgents_cb();
            this.agentGraphChanged += new EventHandler(genAgentsGraphEvent);

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            state_machine_tv.Visibility = System.Windows.Visibility.Hidden;
            attributes_lb.Visibility = System.Windows.Visibility.Hidden;
            add_att_b.Visibility = System.Windows.Visibility.Hidden;
            refresh_att_b.Visibility = System.Windows.Visibility.Hidden;
            policies_lb.Visibility = System.Windows.Visibility.Hidden;
            new_policy_b.Visibility = System.Windows.Visibility.Hidden;
            new_aggregationrule_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

        }

        private void pause_sim_b_Click(object sender, RoutedEventArgs e)
        {
            if(timer != null)
                timer.Stop();
            play_sim_b.IsEnabled = true;

        }
        
        private void play_sim_b_Click(object sender, RoutedEventArgs e)
        {
            playCall();           
        }

        private void playCall()
        {
            if (allAgents == null)
            {
                allAgents = new List<Agent>();

                foreach (string agentName in agentNames)
                {
                    //Agent agent = MisUseAnObjectsDB.loadGroupAgentDBAgent(agentName, MainWindow.clusterName);
                    Agent agent = MisUseAnObjectsDB.loadAgentDB(agentName, MainWindow.clusterName);
                    allAgents.Add(agent);
                }
            }

            if (groupFunctions == null)
                groupFunctions = MisUseAnObjectsDB.loadAllGroupFunctions(MainWindow.clusterName);
            if (groupNames == null)
                groupNames = MisUseAnObjectsDB.loadAllGroupNamesDB(MainWindow.clusterName);

            if (contextInstance == null)
                contextInstance = new Context(allAgents, groupFunctions, groupNames);
            if (misuseAnalyser == null)
                misuseAnalyser = new MisuseAnalyser();
            if (aggregationMisuseAnalyser == null)
                aggregationMisuseAnalyser = new VulnerabilityAnalyser();

            if (source_agent != null)
            {
                agentGraphRedraw();
            }
            play_sim_b.IsEnabled = false;
        }

        private void stop_sim_b_Click(object sender, RoutedEventArgs e)
        {
            if (timer != null)
            {
                timer.Stop();
                timer = null;
                agentsGraph = null;
                contextInstance = null;
                misuseAnalyser = null;
                aggregationMisuseAnalyser = null;
                groupFunctions = null;
                groupNames = null;
                allAgents = null;

                stopCall = true;

                int_seq_no = 1;
                //specific_context_lb.Items.Clear();
                specific_lb_1.Items.Clear();
                general_context_lb.Items.Clear();

                genStateMachineGraph(source_agent_name); 
                genAgentsGraph();
                stopCall = false;
            }
            play_sim_b.IsEnabled = true;       
        }

        
        void genAgentsGraphEvent(object sender, EventArgs e)
        {
            if (timer == null)
            {
                timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromMilliseconds(1000*2);
                timer.Tick += new EventHandler(someEventHandler);
            }            
            timer.Start();                       
        }

        private void someEventHandler(Object sender, EventArgs args)
        {
            seqTimeline = seqTimeline + 1;

            List<Object> parameterisedContextInstances_ = contextInstance.generateParamaterisedEnvAttInstances();
            Dictionary<Dictionary<Agent, Agent>, ListDictionary> sendReceiveContextAgent = contextInstance.generateInteractionInstance(parameterisedContextInstances_, source_agent);
                        
            bool sendRecSame = true;
            while (sendRecSame)
            {
                sendAgent = null;
                receiveAgent = null;
                subjectAgent = null;
                message_s = null;
                message_t = null;

                foreach (KeyValuePair<Dictionary<Agent, Agent>, ListDictionary> pair in sendReceiveContextAgent)
                {
                    Dictionary<Agent, Agent> messageHeader = pair.Key;
                    foreach (KeyValuePair<Agent, Agent> sr in messageHeader)
                    {
                        sendAgent = sr.Key;
                        receiveAgent = sr.Value;                       
                    }

                    ListDictionary messageBody = pair.Value;
                    foreach (DictionaryEntry mes in messageBody)
                    {
                        subjectAgent = (Agent)mes.Key;
                        subjectAgent.timestamp = DateTime.Now;

                        if (mes.Value is State)
                        {
                            message_s = (State)mes.Value;
                            message_t = null;
                        }
                        else if (mes.Value is Transition)
                        {
                            message_t = (Transition)mes.Value;
                            message_s = null;
                        }

                    }
                }
                
                if (sendAgent.agentName.Equals(receiveAgent.agentName))
                {
                    sendReceiveContextAgent = contextInstance.generateInteractionInstance(parameterisedContextInstances_, source_agent);
                }
                else if (message_s != null && message_s.activeAction == null)
                {
                    sendReceiveContextAgent = contextInstance.generateInteractionInstance(parameterisedContextInstances_, source_agent);
                }
                else if (message_s != null && message_s.activeAction.parameterisedOperationalAttributes.Count == 0)
                {
                    sendReceiveContextAgent = contextInstance.generateInteractionInstance(parameterisedContextInstances_, source_agent);
                }
                else if (message_t != null && message_t.activeEvent == null)
                {
                    sendReceiveContextAgent = contextInstance.generateInteractionInstance(parameterisedContextInstances_, source_agent);
                }
                else if (message_t != null && message_t.activeEvent.parameterisedOperationalAttributes.Count == 0)
                {
                    sendReceiveContextAgent = contextInstance.generateInteractionInstance(parameterisedContextInstances_, source_agent);
                }
                else
                {
                    sendRecSame = false;
                }
            }


            //correlate parameterised context with attributes in message_s/t
            if (message_s != null)
            {
                foreach (Attribute att in message_s.activeAction.parameterisedOperationalAttributes)
                {
                    foreach (Object obj in parameterisedContextInstances_)
                    {
                        Attribute att_p = obj as Attribute;
                        if (att_p != null)
                        {
                            if (att.name.Equals(att_p.name))
                            {
                                ////for smartParking demo only
                                if (att.name.Equals("SubjectName"))
                                {
                                    att.activeDomain = subjectAgent.agentName;
                                }
                                else if (att.name.Equals("SenderName"))
                                {
                                    att.activeDomain = sendAgent.agentName;
                                }
                                else if (att.name.Equals("ReceiverName"))
                                {
                                    att.activeDomain = receiveAgent.agentName;
                                }
                                ////

                                //set sensitivity and Obfuscation levels
                                contextInstance.setSensitivityObfuscationLevels(att);
                                att_p.sensitivityLevel = att.sensitivityLevel;
                                att_p.obfuscationLevel = att.obfuscationLevel;
                                ////

                                att_p.activeDomain = att.activeDomain;
                                parameterisedContextInstances_.Remove(att_p);
                                parameterisedContextInstances_.Add(att);

                                
                                break;
                            }
                        }
                    }
                }
            }
            else if (message_t != null)
            {
                foreach (Attribute att in message_t.activeEvent.parameterisedOperationalAttributes)
                {
                    foreach (Object obj in parameterisedContextInstances_)
                    {
                        Attribute att_p = obj as Attribute;
                        if (att_p != null)
                        {
                            if (att.name.Equals(att_p.name))
                            {
                                ////for smartParking demo only
                                if (att.name.Equals("SubjectName"))
                                {
                                    att.activeDomain = subjectAgent.agentName;
                                }
                                else if (att.name.Equals("SenderName"))
                                {
                                    att.activeDomain = sendAgent.agentName;
                                }
                                else if (att.name.Equals("ReceiverName"))
                                {
                                    att.activeDomain = receiveAgent.agentName;
                                }
                                ////

                                //set sensitivity and Obfuscation levels
                                contextInstance.setSensitivityObfuscationLevels(att);
                                att_p.sensitivityLevel = att.sensitivityLevel;
                                att_p.obfuscationLevel = att.obfuscationLevel;
                                ////

                                att_p.activeDomain = att.activeDomain;
                                parameterisedContextInstances_.Remove(att_p);
                                parameterisedContextInstances_.Add(att);
                                break;
                            }
                        }
                    }
                }
            }
            /////

            if (sendAgent.agentName.Equals(source_agent_name) || subjectAgent.agentName.Equals(source_agent_name) || receiveAgent.agentName.Equals(source_agent_name))
            {

                //this.Dispatcher.Invoke(new System.Action(() => misuseAnalyser.IdentifyMisuse(source_agent, sendAgent, receiveAgent,
                //                                subjectAgent, message_s, message_t, parameterisedContextInstances, sendReceiveContextAgent)), DispatcherPriority.Normal, null);

                misuseAnalyser.IdentifyMisuse(source_agent, sendAgent, receiveAgent,
                                                subjectAgent, message_s, message_t, parameterisedContextInstances_, sendReceiveContextAgent, contextInstance);
                
            }
            ListDictionary h_item = new ListDictionary();
            h_item.Add(parameterisedContextInstances_, sendReceiveContextAgent);
            HistoryItem hi = new HistoryItem(h_item);
            string sq = "" + interactionSeqNo;
            HistorySerialisationEngine.serialise(sq, sourceAgentName, hi);
            
            interactionSeqNo = interactionSeqNo + 1;
            
           // contextInstance.transmissionHistory.Push(historyItem);

            contextInstance.currentParameterisedContextInstances = parameterisedContextInstances_;
            contextInstance.currentSendReceiveContextAgent = sendReceiveContextAgent;

            //this.Dispatcher.Invoke(new System.Action(() => updateContextInteractionHistory()), DispatcherPriority.Normal, null);
            updateContextInteractionHistory(parameterisedContextInstances_,sendReceiveContextAgent);
            if (misuseAnalyser.misuseFound || misuseAnalyser.potentialMisuseFound)
            {
                //this.Dispatcher.Invoke(new System.Action(() => updateAnalysisThreatHistory()), DispatcherPriority.Normal, null);
                updateAnalysisThreatHistory(parameterisedContextInstances_, sendReceiveContextAgent);

                //tabControl2.SelectedIndex = 0;
            }
            else
            {
                //tabControl2.SelectedIndex = 1;
            }

            //this.Dispatcher.Invoke(new System.Action(() => genAgentsGraph()), DispatcherPriority.Normal, null);
            genAgentsGraph();

            if (misuseAnalyser.misuseFound || misuseAnalyser.potentialMisuseFound)
            {
                if (timer != null)
                    timer.Stop();
                play_sim_b.IsEnabled = true;

                misuseAnalyser.misuseFound = false;
                misuseAnalyser.potentialMisuseFound = false;

            }
            if (aggregationMisuseAnalyser.misuseFound || aggregationMisuseAnalyser.potentialMisuseFound)
            {
                if (timer != null)
                    timer.Stop();
                play_sim_b.IsEnabled = true;

                aggregationMisuseAnalyser.misuseFound = false;
                aggregationMisuseAnalyser.potentialMisuseFound = false;
            }
            parameterisedContextInstances_ = null;
            sendReceiveContextAgent = null;
        }

        public void updateAnalysisThreatHistory(List<Object> parameterisedContextInstances_, 
            Dictionary<Dictionary<Agent, Agent>, ListDictionary> sendReceiveContextAgent)
        {
            threat_history_lb.Items.Clear();
            int index = 1;

            foreach (List<Threat> threats in misuseAnalyser.threats)
            {
                string violatingPolicyStatement = "";
                string threatMessageTransition = "";
                string violatingContext = "";
                string rationale = "";

                List<string> tempTList = new List<string>();

                foreach (Threat threat in threats)
                {

                    string aggStatement = (string)threat.rationales["inference:"];
                    if (aggStatement != null && aggStatement.Length > 0) //true for only aggregation analysis
                    {
                        violatingPolicyStatement = violatingPolicyStatement + aggStatement;
                        violatingPolicyStatement = violatingPolicyStatement + "\n";
                    }


                    PolicyStatementAnalyser psa = new PolicyStatementAnalyser();
                    psa.ifThenUnlessTokenisation(threat.violatedPolicy.statement);
                    string if_content = "IF" + psa.if_content;
                    string then_content = "   THEN" + psa.then_content;
                    string unless_content = "   UNLESS" + psa.unless_content;

                    string temp_s = "";
                    temp_s = temp_s + if_content + then_content;
                    if(unless_content != null)
                        temp_s = temp_s + "\r\n" + unless_content;

                    bool contained = false;
                    foreach (string ts in tempTList)
                    {
                        if (ts.Equals(temp_s))
                        {
                            contained = true;
                            break;
                        }
                    }

                    if (contained == false || (aggStatement != null && aggStatement.Length > 0))
                    {
                        tempTList.Add(temp_s);

                        violatingPolicyStatement = violatingPolicyStatement + if_content + "\n" + then_content;

                        if (psa.unless_content != null && psa.unless_content.Count() > 0)
                        {
                            violatingPolicyStatement = violatingPolicyStatement + "\n" + unless_content;
                        }
                        violatingPolicyStatement = violatingPolicyStatement + "\n";
                        violatingPolicyStatement = violatingPolicyStatement + "RATIONALE: " + threat.comments;
                        violatingPolicyStatement = violatingPolicyStatement + "\n-------------------------------------------\n";
                    }
                }
                TextBlock violatedPolicy_tb = new TextBlock();
                violatedPolicy_tb.Text = violatingPolicyStatement;
                violatedPolicy_tb.Width = threat_history_lb.Width * 3 / 4 - 20;
                violatedPolicy_tb.FontSize = 11;
                violatedPolicy_tb.TextWrapping = TextWrapping.Wrap;

                foreach (Threat threat in threats)
                {
                    if (threat.comments.Equals("UNFULFILLED-OBLIGATION") || threat.comments.Equals("INFERRED-AUTHORISATION-FAILURE"))
                    {
                        threatMessageTransition = threatMessageTransition + threat.sendAgent.agentName + "→[";
                        threatMessageTransition = threatMessageTransition + threat.subjectAgent.agentName + "(";
                        State activeState = null;
                        Transition activeTransition = null;

                        if (threat.message_s != null)
                        {
                            activeState = threat.message_s;
                            int i = 0;
                            if (activeState.activeAction != null)
                            {
                                int km = 0;
                                foreach (Attribute att in activeState.activeAction.parameterisedOperationalAttributes)
                                {
                                    threatMessageTransition = threatMessageTransition + att.name + "=" + att.activeDomain;

                                    if (i < activeState.activeAction.parameterisedOperationalAttributes.Count - 1)
                                    {
                                        threatMessageTransition = threatMessageTransition + ",";
                                    }
                                    //if (km == 4)
                                    //{
                                    //    threatMessageTransition = threatMessageTransition + "\r" + "    ";
                                    //    km = 0;
                                    //}
                                    km = km + 1;
                                    i = i + 1;
                                }
                            }
                        }
                        else if (threat.message_t != null)
                        {
                            activeTransition = threat.message_t;
                            int i = 0;
                            if (activeTransition.activeEvent != null)
                            {
                                int km = 0;
                                foreach (Attribute att in activeTransition.activeEvent.parameterisedOperationalAttributes)
                                {
                                    threatMessageTransition = threatMessageTransition + att.name + "=" + att.activeDomain;

                                    if (i < activeTransition.activeEvent.parameterisedOperationalAttributes.Count - 1)
                                    {
                                        threatMessageTransition = threatMessageTransition + ",";
                                    }
                                    //if (km == 4)
                                    //{
                                    //    threatMessageTransition = threatMessageTransition + "\r" + "    ";
                                    //    km = 0;
                                    //}
                                    km = km + 1;

                                    i = i + 1;
                                }
                            }
                        }
                        threatMessageTransition = threatMessageTransition + ")]→" + threat.recieveAgent.agentName;

                        if (threat.message_s != null)
                        {
                            threatMessageTransition = threatMessageTransition + "       #:" + threat.message_s.name;
                        }
                        else if (threat.message_t != null)
                        {
                            threatMessageTransition = threatMessageTransition + "       #:" + threat.message_t.transitionName;
                        }

                        threatMessageTransition = threatMessageTransition + "\r\n";
                    }
                    if (threatMessageTransition.Length > 0)
                    {
                        break;
                    }
                }
                if (threatMessageTransition.Length == 0) // use obligation failure only if there is no authorisation failure
                {
                    foreach (Threat threat in threats)
                    {
                        threatMessageTransition = threatMessageTransition + threat.sendAgent.agentName + "→[";
                        threatMessageTransition = threatMessageTransition + threat.subjectAgent.agentName + "(";
                        State activeState = null;
                        Transition activeTransition = null;

                        if (threat.message_s != null)
                        {
                            activeState = threat.message_s;
                            int i = 0;
                            if (activeState.activeAction != null)
                            {
                                int km = 0;
                                foreach (Attribute att in activeState.activeAction.parameterisedOperationalAttributes)
                                {
                                    threatMessageTransition = threatMessageTransition + att.name + "=" + att.activeDomain;

                                    if (i < activeState.activeAction.parameterisedOperationalAttributes.Count - 1)
                                    {
                                        threatMessageTransition = threatMessageTransition + ",";
                                    }
                                    //if (km == 4)
                                    //{
                                    //    threatMessageTransition = threatMessageTransition + "\r" + "    ";
                                    //    km = 0;
                                    //}
                                    km = km + 1;
                                    i = i + 1;
                                }
                            }
                        }
                        else if (threat.message_t != null)
                        {
                            activeTransition = threat.message_t;
                            int i = 0;
                            if (activeTransition.activeEvent != null)
                            {
                                int km = 0;
                                foreach (Attribute att in activeTransition.activeEvent.parameterisedOperationalAttributes)
                                {
                                    threatMessageTransition = threatMessageTransition + att.name + "=" + att.activeDomain;

                                    if (i < activeTransition.activeEvent.parameterisedOperationalAttributes.Count - 1)
                                    {
                                        threatMessageTransition = threatMessageTransition + ",";
                                    }
                                    //if (km == 4)
                                    //{
                                    //    threatMessageTransition = threatMessageTransition + "\r" + "    ";
                                    //    km = 0;
                                    //}
                                    km = km + 1;

                                    i = i + 1;
                                }
                            }
                        }
                        threatMessageTransition = threatMessageTransition + ")]→" + threat.recieveAgent.agentName;

                        if (threat.message_s != null)
                        {
                            threatMessageTransition = threatMessageTransition + "       #:" + threat.message_s.name;
                        }
                        else if (threat.message_t != null)
                        {
                            threatMessageTransition = threatMessageTransition + "       #:" + threat.message_t.transitionName;
                        }

                        threatMessageTransition = threatMessageTransition + "\r\n";
                        if (threatMessageTransition.Length > 0)
                        {
                            break;
                        }
                    }
                }                

                TextBlock threatMessageTransition_tb = new TextBlock();
                threatMessageTransition_tb.Text = threatMessageTransition;
                threatMessageTransition_tb.Width = threat_history_lb.Width * 3 / 4 - 20;
                threatMessageTransition_tb.TextWrapping = TextWrapping.Wrap;
                threatMessageTransition_tb.Foreground = Brushes.Red;

                int j = 0;
                //int k = 0;

                foreach (Threat threat in threats)
                {
                    if (threat.comments.Equals("UNFULFILLED-OBLIGATION") || threat.comments.Equals("INFERRED-AUTHORISATION-FAILURE"))
                    {
                        
                        foreach (Object obj in threat.violatingParameterisedContextInstances)
                        {
                            Attribute atte = obj as Attribute;
                            if (atte != null)
                            {
                                if (atte.activeDomain != null && atte.activeDomain.Count() > 0)
                                {
                                    violatingContext = violatingContext + atte.name + "=" + atte.activeDomain;
                                }
                                else
                                {
                                    violatingContext = violatingContext + atte.name + "= ?";
                                }
                            }
                            else
                            {
                                GroupFunction gf = obj as GroupFunction;
                                if (gf != null)
                                {
                                    string membershipFunction = gf.functionName + "(" + gf.agentName + ", " + gf.groupName + ")";
                                    violatingContext = violatingContext + membershipFunction;
                                }
                            }

                            if (j < parameterisedContextInstances_.Count() - 1)
                            {
                                violatingContext = violatingContext + ", ";
                            }                    
                            j = j + 1;
                        }
                    }
                    if (violatingContext.Length > 0)
                    {
                        break;
                    }
                }
                if (violatingContext.Length == 0)
                {
                    foreach (Threat threat in threats)
                    {

                        foreach (Object obj in threat.violatingParameterisedContextInstances)
                        {
                            Attribute atte = obj as Attribute;
                            if (atte != null)
                            {
                                if (atte.activeDomain != null && atte.activeDomain.Count() > 0)
                                {
                                    violatingContext = violatingContext + atte.name + "=" + atte.activeDomain;
                                }
                                else
                                {
                                    violatingContext = violatingContext + atte.name + "= ?";
                                }
                            }
                            else
                            {
                                GroupFunction gf = obj as GroupFunction;
                                if (gf != null)
                                {
                                    string membershipFunction = gf.functionName + "(" + gf.agentName + ", " + gf.groupName + ")";
                                    violatingContext = violatingContext + membershipFunction;
                                }
                            }

                            if (j < parameterisedContextInstances_.Count() - 1)
                            {
                                violatingContext = violatingContext + ", ";
                            }
                            j = j + 1;
                            //if (k == 3)
                            //{
                            //    violatingContext = violatingContext + "\r";
                            //    k = 0;
                            //}
                            //else
                            //{
                            //    k = k + 1;
                            //}
                        }
                        if (violatingContext.Length > 0)
                        {
                            break;
                        }
                    }
                }

                violatingContext = violatingContext + "\r\n";

                TextBlock violatingContext_tb = new TextBlock();
                violatingContext_tb.Text = violatingContext;
                violatingContext_tb.Width = threat_history_lb.Width * 3 / 4 - 20;
                violatingContext_tb.TextWrapping = TextWrapping.Wrap;
                violatingContext_tb.Foreground = Brushes.Red;

                //rationale = threat.rationalle;

                //TextBlock rationale_tb = new TextBlock();
                //rationale_tb.Text = rationale; 
                //rationale_tb.Width = threat_history_lb.Width -10;
                //rationale_tb.TextWrapping = TextWrapping.Wrap;
                
                ContentPresenter no_index_cp = new ContentPresenter();
                no_index_cp.Content = index+".";
                index = index + 1;
                ContentPresenter transmissionMessage_cp = new ContentPresenter();
                transmissionMessage_cp.Content = threatMessageTransition_tb;
                ContentPresenter violatedPolicy_cp = new ContentPresenter();
                violatedPolicy_cp.Content = violatedPolicy_tb;
                ContentPresenter violatingContext_cp = new ContentPresenter();
                violatingContext_cp.Content = violatingContext_tb;
                //ContentPresenter rationale_cp = new ContentPresenter();
                //rationale_cp.Content = rationale_tb;

                //ContentPresenter violate_image_cp = new ContentPresenter();
                //BitmapImage cm_i_image = new BitmapImage();
                //cm_i_image.BeginInit();
                //Uri cm_i_Uri = new Uri("/PMisuseAn;component/images/Error.ico", UriKind.RelativeOrAbsolute);
                //cm_i_image.UriSource = cm_i_Uri;
                //cm_i_image.EndInit();

                //Image cm_i_iconImage = new Image();
                //cm_i_iconImage.Source = cm_i_image;
                //violate_image_cp.Content = cm_i_iconImage;
               
                no_index_cp.Width = threat_history_lb.Width * 1 / 27;
                transmissionMessage_cp.Width = threat_history_lb.Width * 3 / 4 - 13;
                violatedPolicy_cp.Width = threat_history_lb.Width * 3 / 4 - 13;
                violatingContext_cp.Width = threat_history_lb.Width * 3 / 4 - 13;
                //rationale_cp.Width = threat_history_lb.Width * 3 / 4 - 41;
                //violate_image_cp.Width = 20;
                
                ListBoxItem l = new ListBoxItem();
                StackPanel s = new StackPanel();
                s.Orientation = System.Windows.Controls.Orientation.Vertical;
                               
                //ContentPresenter headerNo = new ContentPresenter();
                //headerNo.Content = "NO:";
                //headerNo.Width = threat_history_lb.Width * 1 / 8 - 5;

                ContentPresenter headerViolatingContext = new ContentPresenter();
                headerViolatingContext.Content = "Threatening"+"\r\n"+"Context:";
                headerViolatingContext.Width = threat_history_lb.Width * 1 / 6 - 3;

                ContentPresenter headerMessageTransfer = new ContentPresenter();
                headerMessageTransfer.Content = "Information"+"\r\n"+"Transfer:";
                headerMessageTransfer.Width = threat_history_lb.Width * 1 / 6 - 3;

                ContentPresenter headerVoilatedPolicy = new ContentPresenter();
                headerVoilatedPolicy.Content = "Violated"+"\r\n"+"Policy:";
                headerVoilatedPolicy.Width = threat_history_lb.Width * 1 / 6 - 3;

                //ContentPresenter headerRationale = new ContentPresenter();
                //headerRationale.Content = "Threat:";
                //headerRationale.Width = threat_history_lb.Width * 1 / 6 - 3;

                //ListBoxItem l_no = new ListBoxItem();
                StackPanel s_super = new StackPanel();
                
                s_super.Orientation = System.Windows.Controls.Orientation.Horizontal;
                //s_super.Children.Add(headerNo);
                s_super.Children.Add(no_index_cp);

                //l_no.Content = s_super;
                //s.Children.Add(l_no);

                ListBoxItem l_v_context = new ListBoxItem();
                StackPanel s_v_context = new StackPanel();
                s_v_context.Orientation = System.Windows.Controls.Orientation.Horizontal;
                s_v_context.Children.Add(headerViolatingContext);
                s_v_context.Children.Add(violatingContext_cp);
                l_v_context.Content = s_v_context;
                s.Children.Add(l_v_context);

                ListBoxItem l_mess= new ListBoxItem();
                StackPanel s_mess = new StackPanel();
                s_mess.Orientation = System.Windows.Controls.Orientation.Horizontal;
                s_mess.Children.Add(headerMessageTransfer);
                s_mess.Children.Add(transmissionMessage_cp);
                l_mess.Content = s_mess;
                s.Children.Add(l_mess);

                ListBoxItem l_pol = new ListBoxItem();
                StackPanel s_pol = new StackPanel();
                s_pol.Orientation = System.Windows.Controls.Orientation.Horizontal;
                s_pol.Children.Add(headerVoilatedPolicy);
                s_pol.Children.Add(violatedPolicy_cp);
                l_pol.Content = s_pol;
                s.Children.Add(l_pol);

                ListBoxItem l_rat = new ListBoxItem();
                StackPanel s_rat = new StackPanel();
                s_rat.Orientation = System.Windows.Controls.Orientation.Horizontal;
                //s_rat.Children.Add(headerRationale);
                //s_rat.Children.Add(rationale_cp);
                l_rat.Content = s_rat;
                s.Children.Add(l_rat);

                s_super.Children.Add(s);

                //s_super.Children.Add(violate_image_cp);

                if (threat_history_lb.Items.Count % 2 == 0)
                {
                    l.Background = Brushes.AliceBlue;
                }
                l.Tag = threats;

                //l.Foreground = Brushes.Red;
                l.Content = s_super;
                l.Tag = threats;
                //l.FontSize = 11;
                //l.Dispatcher.Invoke(new System.Action(() => l.AddHandler(ListBoxItem.SelectedEvent, new RoutedEventHandler(threatHistoryLBItemSelected))), DispatcherPriority.Normal, null);
              
                this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.Items.Add(l)), DispatcherPriority.Normal, null);
                //this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.SelectedIndex = general_context_lb.Items.Count-1), DispatcherPriority.Normal, null);            
                this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.ScrollIntoView(threat_history_lb.Items[threat_history_lb.Items.Count - 1])), DispatcherPriority.Normal, null);

                //mitigate threat
                mitigationEnforcementSelection(threats, violatingPolicyStatement, threatMessageTransition, violatingContext, rationale);
            }

            ////////
            //foreach (Threat threat in misuseAnalyser.cachePotentialThreats)
            //{
            //    string violatingPolicyStatement = null;
            //    string threatMessageTransition = null;
            //    string violatingContext = null;
            //    string rationale = "";

            //    PolicyStatementAnalyser psa = new PolicyStatementAnalyser();
            //    psa.ifThenUnlessTokenisation(threat.violatedPolicy.statement);
            //    string if_content = "IF" + psa.if_content;
            //    string then_content = "   THEN" + psa.then_content;
            //    string unless_content = "   UNLESS" + psa.unless_content;

            //    violatingPolicyStatement = if_content + Environment.NewLine + then_content;
            //    if (psa.unless_content != null && psa.unless_content.Count() > 0)
            //    {
            //        violatingPolicyStatement = violatingPolicyStatement + Environment.NewLine + unless_content;
            //    }
            //    violatingPolicyStatement = violatingPolicyStatement + "\r\n";

            //    TextBlock violatedPolicy_tb = new TextBlock();
            //    violatedPolicy_tb.Text = violatingPolicyStatement;
            //    //violatedPolicy_tb.Width = threat_history_lb.Width - 10;
            //    violatedPolicy_tb.Width = threat_history_lb.Width * 3 / 4 - 20;
            //    violatedPolicy_tb.TextWrapping = TextWrapping.Wrap;


            //    threatMessageTransition = threatMessageTransition + threat.sendAgent.agentName + "→[";
            //    threatMessageTransition = threatMessageTransition + threat.subjectAgent.agentName + "(";
            //    State activeState = null;
            //    Transition activeTransition = null;

            //    if (threat.message_s != null)
            //    {
            //        activeState = threat.message_s;
            //        int i = 0;
            //        if (activeState.activeAction != null)
            //        {
            //            int km = 0;
            //            foreach (Attribute att in activeState.activeAction.parameterisedOperationalAttributes)
            //            {
            //                threatMessageTransition = threatMessageTransition + att.name + "=" + att.activeDomain;

            //                if (i < activeState.activeAction.parameterisedOperationalAttributes.Count - 1)
            //                {
            //                    threatMessageTransition = threatMessageTransition + ",";
            //                }

            //                //if (km == 4)
            //                //{
            //                //    threatMessageTransition = threatMessageTransition + "\r" + "    ";
            //                //    km = 0;
            //                //}
            //                km = km + 1;

            //                i = i + 1;
            //            }
            //        }
            //    }
            //    else if (threat.message_t != null)
            //    {
            //        activeTransition = threat.message_t;
            //        int i = 0;
            //        if (activeTransition.activeEvent != null)
            //        {
            //            int km = 0;
            //            foreach (Attribute att in activeTransition.activeEvent.parameterisedOperationalAttributes)
            //            {
            //                threatMessageTransition = threatMessageTransition + att.name + "=" + att.activeDomain;

            //                if (i < activeTransition.activeEvent.parameterisedOperationalAttributes.Count - 1)
            //                {
            //                    threatMessageTransition = threatMessageTransition + ",";
            //                }

            //                //if (km == 4)
            //                //{
            //                //    threatMessageTransition = threatMessageTransition + "\r" + "    ";
            //                //    km = 0;
            //                //}
            //                km = km + 1;

            //                i = i + 1;
            //            }
            //        }
            //    }
            //    threatMessageTransition = threatMessageTransition + ")]→" + threat.recieveAgent.agentName;

            //    if (threat.message_s != null)
            //    {
            //        threatMessageTransition = threatMessageTransition + "        #:" + threat.message_s.name;
            //    }
            //    else if (threat.message_t != null)
            //    {
            //        threatMessageTransition = threatMessageTransition + "        #:" + threat.message_t.transitionName;
            //    }
            //    threatMessageTransition = threatMessageTransition + "\r\n";

            //    TextBlock threatMessageTransition_tb = new TextBlock();
            //    threatMessageTransition_tb.Text = threatMessageTransition;
            //    //threatMessageTransition_tb.Width = threat_history_lb.Width - 10;
            //    threatMessageTransition_tb.Width = threat_history_lb.Width * 3 / 4 - 20;
            //    threatMessageTransition_tb.TextWrapping = TextWrapping.Wrap;

            //    int j = 0;
            //    int m = 0;
            //    foreach (Object obj in threat.violatingParameterisedContextInstances)
            //    {
            //        Attribute atte = obj as Attribute;
            //        if (atte != null)
            //        {
            //            if (atte.activeDomain != null && atte.activeDomain.Count() > 0)
            //            {
            //                violatingContext = violatingContext + atte.name + "=" + atte.activeDomain;
            //            }
            //            else
            //            {
            //                violatingContext = violatingContext + atte.name + "= ?";
            //            }
            //        }
            //        else
            //        {
            //            GroupFunction gf = obj as GroupFunction;
            //            if (gf != null)
            //            {
            //                string membershipFunction = gf.functionName + "(" + gf.agentName + ", " + gf.groupName + ")";
            //                violatingContext = violatingContext + membershipFunction;
            //            }
            //        }

            //        if (j < parameterisedContextInstances_.Count() - 1)
            //        {
            //            violatingContext = violatingContext + ", ";
            //        }
            //        j = j + 1;

            //        //if (m == 3)
            //        //{
            //        //    violatingContext = violatingContext + "\r";
            //        //    m = 0;
            //        //}
            //        //else
            //        //{
            //        //    m = m + 1;
            //        //}
            //    }
            //    violatingContext = violatingContext + "\r\n";

            //    TextBlock violatingContext_tb = new TextBlock();
            //    violatingContext_tb.Text = violatingContext;
            //    //violatingContext_tb.Width = threat_history_lb.Width - 10;
            //    violatingContext_tb.Width = threat_history_lb.Width * 3 / 4 - 20;
            //    violatingContext_tb.TextWrapping = TextWrapping.Wrap;

            //    rationale = threat.rationalle;

            //    //TextBlock rationale_tb = new TextBlock();
            //    //rationale_tb.Text = rationale;
            //    //rationale_tb.Width = threat_history_lb.Width - 10;
            //    //rationale_tb.TextWrapping = TextWrapping.Wrap;

            //    ContentPresenter no_index_cp = new ContentPresenter();
            //    no_index_cp.Content = index + ".";
            //    index = index + 1;
            //    ContentPresenter transmissionMessage_cp = new ContentPresenter();
            //    transmissionMessage_cp.Content = threatMessageTransition_tb;
            //    ContentPresenter violatedPolicy_cp = new ContentPresenter();
            //    violatedPolicy_cp.Content = violatedPolicy_tb;
            //    ContentPresenter violatingContext_cp = new ContentPresenter();
            //    violatingContext_cp.Content = violatingContext_tb;
            //    //ContentPresenter rationale_cp = new ContentPresenter();
            //    //rationale_cp.Content = rationale_tb;

            //    //ContentPresenter violate_image_cp = new ContentPresenter();
            //    //BitmapImage cm_i_image = new BitmapImage();
            //    //cm_i_image.BeginInit();
            //    //Uri cm_i_Uri = new Uri("/PMisuseAn;component/images/Warning.ico", UriKind.RelativeOrAbsolute);
            //    //cm_i_image.UriSource = cm_i_Uri;
            //    //cm_i_image.EndInit();

            //    //Image cm_i_iconImage = new Image();
            //    //cm_i_iconImage.Source = cm_i_image;
            //    //violate_image_cp.Content = cm_i_iconImage;
                
            //    no_index_cp.Width = threat_history_lb.Width * 1 / 27;
            //    transmissionMessage_cp.Width = threat_history_lb.Width * 3 / 4 - 13;
            //    violatedPolicy_cp.Width = threat_history_lb.Width * 3 / 4 - 13;
            //    violatingContext_cp.Width = threat_history_lb.Width * 3 / 4 - 13;
            //    //rationale_cp.Width = threat_history_lb.Width * 3 / 4 - 41;
            //    //violate_image_cp.Width = 20;

            //    ListBoxItem l = new ListBoxItem();
            //    StackPanel s = new StackPanel();
            //    s.Orientation = System.Windows.Controls.Orientation.Vertical;

            //    //ContentPresenter headerNo = new ContentPresenter();
            //    //headerNo.Content = "NO:";
            //    //headerNo.Width = threat_history_lb.Width * 1 / 8 - 5;

            //    ContentPresenter headerViolatingContext = new ContentPresenter();
            //    headerViolatingContext.Content = "Threatening"+"\r\n"+"Context:";
            //    headerViolatingContext.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    ContentPresenter headerMessageTransfer = new ContentPresenter();
            //    headerMessageTransfer.Content = "Information" + "\r\n" + "Transfer:";
            //    headerMessageTransfer.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    ContentPresenter headerVoilatedPolicy = new ContentPresenter();
            //    headerVoilatedPolicy.Content = "Violated"+"\r\n"+"Policy:";
            //    headerVoilatedPolicy.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    //ContentPresenter headerRationale = new ContentPresenter();
            //    //headerRationale.Content = "Potential"+"\r\n"+"Threat:";
            //    //headerRationale.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    //ListBoxItem l_no = new ListBoxItem();
            //    StackPanel s_super = new StackPanel();

            //    s_super.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    //s_super.Children.Add(headerNo);
            //    s_super.Children.Add(no_index_cp);

            //    //l_no.Content = s_super;
            //    //s.Children.Add(l_no);

            //    ListBoxItem l_v_context = new ListBoxItem();
            //    StackPanel s_v_context = new StackPanel();
            //    s_v_context.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    s_v_context.Children.Add(headerViolatingContext);
            //    s_v_context.Children.Add(violatingContext_cp);
            //    l_v_context.Content = s_v_context;
            //    s.Children.Add(l_v_context);

            //    ListBoxItem l_mess = new ListBoxItem();
            //    StackPanel s_mess = new StackPanel();
            //    s_mess.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    s_mess.Children.Add(headerMessageTransfer);
            //    s_mess.Children.Add(transmissionMessage_cp);
            //    //s_mess.Children.Add(violate_image_cp);
            //    l_mess.Content = s_mess;
            //    s.Children.Add(l_mess);

            //    ListBoxItem l_pol = new ListBoxItem();
            //    StackPanel s_pol = new StackPanel();
            //    s_pol.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    s_pol.Children.Add(headerVoilatedPolicy);
            //    s_pol.Children.Add(violatedPolicy_cp);
            //    l_pol.Content = s_pol;
            //    s.Children.Add(l_pol);

            //    ListBoxItem l_rat = new ListBoxItem();
            //    StackPanel s_rat = new StackPanel();
            //    s_rat.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    //s_rat.Children.Add(headerRationale);
            //    //s_rat.Children.Add(rationale_cp);
            //    l_rat.Content = s_rat;
            //    s.Children.Add(l_rat);

            //    s_super.Children.Add(s);

            //    //s_super.Children.Add(violate_image_cp);

            //    if (threat_history_lb.Items.Count % 2 == 0)
            //    {
            //        l.Background = Brushes.AliceBlue;
            //    }
            //    l.Tag = threat;
            //    //l.Dispatcher.Invoke(new System.Action(() => l.AddHandler(ListBoxItem.SelectedEvent, new RoutedEventHandler(threatHistoryLBItemSelected))), DispatcherPriority.Normal, null);
                
            //    //l.Foreground = Brushes.Red;
            //    l.Content = s_super;

            //    this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.Items.Add(l)), DispatcherPriority.Normal, null);
            //    //this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.SelectedIndex = general_context_lb.Items.Count-1), DispatcherPriority.Normal, null);            
            //    this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.ScrollIntoView(threat_history_lb.Items[threat_history_lb.Items.Count - 1])), DispatcherPriority.Normal, null);

            //    //mitigate threat
            //    mitigationEnforcementSelection(threat, violatingPolicyStatement, threatMessageTransition, violatingContext, rationale);
            //}

            ///////////////////////

            //foreach (Threat threat in aggregationMisuseAnalyser.aggregationThreats)
            //{
            //    string violatingPolicyStatement = null;
            //    //string threatMessageTransition_otm = threat.vulnTrans.originalMessage;
            //    string threatMessageTransition_otm = (string)threat.rationales["messageTrans:"];
            //    //string[] threatMessageTransition_ = threatMessageTransition_otm.Split(',');
            //    string threatMessageTransition = threatMessageTransition_otm;
            //    threatMessageTransition = threatMessageTransition + "\r\n";

            //    //string threatMessageTransition = "";
            //    //int count_otm = 0;
            //    //foreach (string sotm in threatMessageTransition_)
            //    //{
            //    //    if (sotm.Trim().Length > 0 && !sotm.Equals("\r") && !sotm.Equals("\r\n"))
            //    //    {
            //    //        threatMessageTransition = threatMessageTransition + sotm + ",";
            //    //        if (count_otm == 3)
            //    //        {
            //    //            threatMessageTransition = threatMessageTransition + "\r\n" + "    ";
            //    //            count_otm = 0;
            //    //        }
            //    //        count_otm = count_otm + 1;
            //    //    }
                    
            //    //}
            //    //string violatingContext = threat.vulnTrans.originalContext;
            //    string violatingContext = (string)threat.rationales["violatingContext:"];

            //    violatingContext = violatingContext + "\r\n";
            //    string rationale = "";

            //    TextBlock violatingContext_tb = new TextBlock();
            //    violatingContext_tb.Text = violatingContext;
            //    violatingContext_tb.Width = threat_history_lb.Width * 3 / 4 - 10;
            //    violatingContext_tb.TextWrapping = TextWrapping.Wrap;
            //    violatingContext_tb.Foreground = Brushes.Red;

            //    TextBlock threatMessageTransition_tb = new TextBlock();
            //    threatMessageTransition_tb.Text = threatMessageTransition;
            //    threatMessageTransition_tb.Width = threat_history_lb.Width * 3 / 4 - 10;
            //    threatMessageTransition_tb.TextWrapping = TextWrapping.Wrap;
            //    threatMessageTransition_tb.Foreground = Brushes.Red;

            //    PolicyStatementAnalyser psa = new PolicyStatementAnalyser();
            //    psa.ifThenUnlessTokenisation(threat.violatedPolicy.statement);
            //    string if_content = "IF" + psa.if_content;
            //    string then_content = "   THEN" + psa.then_content;
            //    string unless_content = "   UNLESS" + psa.unless_content;

            //    violatingPolicyStatement = if_content + Environment.NewLine + then_content;
            //    if (psa.unless_content != null && psa.unless_content.Count() > 0)
            //    {
            //        violatingPolicyStatement = violatingPolicyStatement + Environment.NewLine + unless_content;
            //    }
            //    violatingPolicyStatement = violatingPolicyStatement + "\r\n";

            //    TextBlock violatedPolicy_tb = new TextBlock();
            //    violatedPolicy_tb.Text = violatingPolicyStatement;
            //    violatedPolicy_tb.Width = threat_history_lb.Width * 3 / 4 - 10;
            //    violatedPolicy_tb.TextWrapping = TextWrapping.Wrap;

            //    //string rationaleMessageTransition_o = (string)threat.rationales["Transmission:"];
            //    //string rationaleContextTransition = (string)threat.rationales["HContext:"];
            //    string aggStatement = (string)threat.rationales["inference:"];

            //    //string [] rationaleMessageTransition_ = rationaleMessageTransition_o.Split(',');

            //    //string rationaleMessageTransition = rationaleMessageTransition_o;

            //    //string rationaleMessageTransition = "";
            //    //int count = 0;
            //    //foreach (string so in rationaleMessageTransition_)
            //    //{
            //    //    if (so.Trim().Length > 0 && !so.Equals("\r") && !so.Equals("\r\n"))
            //    //    {
            //    //        rationaleMessageTransition = rationaleMessageTransition + so + ",";
            //    //        if (count == 3)
            //    //        {
            //    //            rationaleMessageTransition = rationaleMessageTransition + "\r\n" + "    ";
            //    //            count = 0;
            //    //        }
            //    //        count = count + 1;
            //    //    }                    
            //    //}

            //    ContentPresenter cp1 = new ContentPresenter();
            //    cp1.Content = "Inference";
            //    ContentPresenter cp2 = new ContentPresenter();
            //    cp2.Content = "    "+aggStatement;
            //    //ContentPresenter cp3 = new ContentPresenter();
            //    //cp3.Content = "PreviousTransmission:";
            //    //ContentPresenter cp4 = new ContentPresenter();
            //    //cp4.Content = "    " + rationaleMessageTransition;
            //    //ContentPresenter cp5 = new ContentPresenter();
            //    //cp5.Content = "UnsatisfyingContext:";
                
            //    //TextBlock cp6_tb = new TextBlock();
            //    //cp6_tb.Text = rationaleContextTransition;
            //    //cp6_tb.FontSize = 10;
            //    //cp6_tb.Width = threat_history_lb.Width - ((threat_history_lb.Width * 1/3) -5);
            //    //cp6_tb.TextWrapping = TextWrapping.Wrap;
            //    //ContentPresenter cp6 = new ContentPresenter();
            //    //cp6.Content = cp6_tb;

            //    StackPanel spcp = new StackPanel();
            //    spcp.Orientation = System.Windows.Controls.Orientation.Vertical;
            //    spcp.Children.Add(cp1);
            //    spcp.Children.Add(cp2);
            //    //spcp.Children.Add(cp3);
            //    //spcp.Children.Add(cp4);
            //    //spcp.Children.Add(cp5);
            //    //spcp.Children.Add(cp6);
            //    spcp.Background = Brushes.LightYellow;    

            //    ////rationaleMessageTransition = "PreviousTransmission:" + Environment.NewLine + rationaleMessageTransition;
            //    ////rationaleContextTransition = "Unsatisfying context:" + Environment.NewLine + rationaleContextTransition;

            //    ////rationale = rationale + Environment.NewLine;
            //    //rationale = rationale + "InferenceViolations" + Environment.NewLine;
            //    //rationale = rationale + aggStatement + Environment.NewLine;
            //    //rationale = rationale + Environment.NewLine;
            //    //rationale = rationale + "PreviousTransmission:" + Environment.NewLine;
            //    //rationale = rationale + rationaleMessageTransition + Environment.NewLine;
            //    //rationale = rationale + Environment.NewLine;
            //    //rationale = rationale + "UnsatisfyingContext:" + Environment.NewLine;
            //    //rationale = rationale + rationaleContextTransition + Environment.NewLine;
            //    ////rationale = threat.rationalle;

            //    //TextBlock rationale_tb = new TextBlock();
            //    //rationale_tb.Text = rationale;
            //    //rationale_tb.FontSize = 10;
            //    //rationale_tb.Width = threat_history_lb.Width - 10;
            //    //rationale_tb.TextWrapping = TextWrapping.Wrap;

            //    ContentPresenter no_index_cp = new ContentPresenter();
            //    no_index_cp.Content = index + ".";
            //    index = index + 1;
            //    ContentPresenter transmissionMessage_cp = new ContentPresenter();
            //    transmissionMessage_cp.Content = threatMessageTransition_tb;
            //    ContentPresenter violatedPolicy_cp = new ContentPresenter();
            //    violatedPolicy_cp.Content = violatedPolicy_tb;
            //    ContentPresenter violatingContext_cp = new ContentPresenter();
            //    violatingContext_cp.Content = violatingContext_tb;
            //    ContentPresenter rationale_cp = new ContentPresenter();
            //    //rationale_cp.Content = rationale_tb;
            //    rationale_cp.Content = spcp;
            //    //rationale_cp.Height = 300;

            //    //ContentPresenter violate_image_cp = new ContentPresenter();
            //    //BitmapImage cm_i_image = new BitmapImage();
            //    //cm_i_image.BeginInit();
            //    //Uri cm_i_Uri = new Uri("/PMisuseAn;component/images/Error.ico", UriKind.RelativeOrAbsolute);
            //    //cm_i_image.UriSource = cm_i_Uri;
            //    //cm_i_image.EndInit();

            //    //Image cm_i_iconImage = new Image();
            //    //cm_i_iconImage.Source = cm_i_image;
            //    //violate_image_cp.Content = cm_i_iconImage;
            //    //violate_image_cp.VerticalAlignment = System.Windows.VerticalAlignment.Center;

            //    no_index_cp.Width = threat_history_lb.Width * 1 / 27;
            //    transmissionMessage_cp.Width = threat_history_lb.Width * 3 / 4 - 13;
            //    violatedPolicy_cp.Width = threat_history_lb.Width * 3 / 4 - 15;
            //    violatingContext_cp.Width = threat_history_lb.Width * 3 / 4 - 13;
            //    rationale_cp.Width = threat_history_lb.Width * 3 / 4 - 41;
            //    //violate_image_cp.Width = 20;

            //    ListBoxItem l = new ListBoxItem();
            //    StackPanel s = new StackPanel();
            //    s.Orientation = System.Windows.Controls.Orientation.Vertical;

            //    //ContentPresenter headerNo = new ContentPresenter();
            //    //headerNo.Content = "NO:";
            //    //headerNo.Width = threat_history_lb.Width * 1 / 8 - 5;

            //    ContentPresenter headerViolatingContext = new ContentPresenter();
            //    headerViolatingContext.Content = "Threatening"+"\r\n"+"Context:";
            //    headerViolatingContext.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    ContentPresenter headerMessageTransfer = new ContentPresenter();
            //    headerMessageTransfer.Content = "Information" + "\r\n" + "Transfer:";
            //    headerMessageTransfer.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    ContentPresenter headerVoilatedPolicy = new ContentPresenter();
            //    headerVoilatedPolicy.Content = "Violated"+"\r\n"+"Policy:";
            //    headerVoilatedPolicy.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    ContentPresenter headerRationale = new ContentPresenter();
            //    headerRationale.Content = Environment.NewLine+"Rationale:";
            //    headerRationale.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    //ListBoxItem l_no = new ListBoxItem();
            //    StackPanel s_super = new StackPanel();

            //    s_super.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    //s_super.Children.Add(headerNo);
            //    s_super.Children.Add(no_index_cp);

            //    //l_no.Content = s_super;
            //    //s.Children.Add(l_no);

            //    ListBoxItem l_v_context = new ListBoxItem();
            //    StackPanel s_v_context = new StackPanel();
            //    s_v_context.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    s_v_context.Children.Add(headerViolatingContext);
            //    s_v_context.Children.Add(violatingContext_cp);
            //    //s_v_context.Children.Add(violate_image_cp);
            //    l_v_context.Content = s_v_context;
            //    s.Children.Add(l_v_context);

            //    ListBoxItem l_mess = new ListBoxItem();
            //    StackPanel s_mess = new StackPanel();
            //    s_mess.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    s_mess.Children.Add(headerMessageTransfer);
            //    s_mess.Children.Add(transmissionMessage_cp);
            //    //s_mess.Children.Add(violate_image_cp);
            //    l_mess.Content = s_mess;
            //    s.Children.Add(l_mess);

            //    ListBoxItem l_pol = new ListBoxItem();
            //    StackPanel s_pol = new StackPanel();
            //    s_pol.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    s_pol.Children.Add(headerVoilatedPolicy);
            //    s_pol.Children.Add(violatedPolicy_cp);
            //    l_pol.Content = s_pol;
            //    s.Children.Add(l_pol);

            //    ListBoxItem l_rat = new ListBoxItem();
            //    StackPanel s_rat = new StackPanel();
            //    s_rat.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    s_rat.Children.Add(headerRationale);
            //    s_rat.Children.Add(rationale_cp);
            //    l_rat.Content = s_rat;
            //    s.Children.Add(l_rat);

            //    s_super.Children.Add(s);

            //    //s_super.Children.Add(violate_image_cp);
            //    s_super.VerticalAlignment = System.Windows.VerticalAlignment.Center;

            //    if (threat_history_lb.Items.Count % 2 == 0)
            //    {
            //        l.Background = Brushes.AliceBlue;
            //    }
            //    l.Tag = threat;

            //    //l.Foreground = Brushes.Red;
            //    l.Content = s_super;
            //    l.Tag = threat;
            //    //l.FontSize = 11;
            //    //l.Dispatcher.Invoke(new System.Action(() => l.AddHandler(ListBoxItem.SelectedEvent, new RoutedEventHandler(threatHistoryLBItemSelected))), DispatcherPriority.Normal, null);

            //    this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.Items.Add(l)), DispatcherPriority.Normal, null);
            //    //this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.SelectedIndex = general_context_lb.Items.Count-1), DispatcherPriority.Normal, null);            
            //    this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.ScrollIntoView(threat_history_lb.Items[threat_history_lb.Items.Count - 1])), DispatcherPriority.Normal, null);

            //    //mitigate threat
            //    mitigationEnforcementSelection(threat, violatingPolicyStatement, threatMessageTransition, violatingContext, rationale);
            //}

            ////////
            //foreach (Threat threat in aggregationMisuseAnalyser.aggregationCachePotentialThreats)
            //{
            //    string violatingPolicyStatement = null;
            //    //string threatMessageTransition_otm = threat.vulnTrans.originalMessage;
            //    string threatMessageTransition_otm = (string)threat.rationales["messageTrans:"];
            //    //string[] threatMessageTransition_ = threatMessageTransition_otm.Split(',');
            //    string threatMessageTransition = threatMessageTransition_otm;
            //    threatMessageTransition = threatMessageTransition + "\r\n";

            //    //string threatMessageTransition = "";
            //    //int count_otm = 0;
            //    //foreach (string sotm in threatMessageTransition_)
            //    //{
            //    //    if (sotm.Trim().Length > 0 && !sotm.Equals("\r") && !sotm.Equals("\r\n"))
            //    //    {
            //    //        threatMessageTransition = threatMessageTransition + sotm + ",";
            //    //        if (count_otm == 3)
            //    //        {
            //    //            threatMessageTransition = threatMessageTransition + "\r\n" + "    ";
            //    //            count_otm = 0;
            //    //        }
            //    //        count_otm = count_otm + 1;
            //    //    }
            //    //}
            //    string violatingContext = (string)threat.rationales["violatingContext:"];
            //    //string violatingContext = threat.vulnTrans.originalContext;
            //    violatingContext = violatingContext + "\r\n";
            //    string rationale = "";
            //    //string rationale = null;

            //    PolicyStatementAnalyser psa = new PolicyStatementAnalyser();
            //    psa.ifThenUnlessTokenisation(threat.violatedPolicy.statement);
            //    string if_content = "IF" + psa.if_content;
            //    string then_content = "   THEN" + psa.then_content;
            //    string unless_content = "   UNLESS" + psa.unless_content;

            //    violatingPolicyStatement = if_content + Environment.NewLine + then_content;
            //    if (psa.unless_content != null && psa.unless_content.Count() > 0)
            //    {
            //        violatingPolicyStatement = violatingPolicyStatement + Environment.NewLine + unless_content;
            //    }
            //    violatingPolicyStatement = violatingPolicyStatement + "\r\n";

            //    TextBlock violatedPolicy_tb = new TextBlock();
            //    violatedPolicy_tb.Text = violatingPolicyStatement;
            //    //violatedPolicy_tb.Width = threat_history_lb.Width - 10;
            //    violatedPolicy_tb.Width = threat_history_lb.Width * 3 / 4 - 10;
            //    violatedPolicy_tb.TextWrapping = TextWrapping.Wrap;
                                
            //    TextBlock threatMessageTransition_tb = new TextBlock();
            //    threatMessageTransition_tb.Text = threatMessageTransition;
            //    //threatMessageTransition_tb.Width = threat_history_lb.Width - 10;
            //    threatMessageTransition_tb.Width = threat_history_lb.Width * 3 / 4 - 10;
            //    threatMessageTransition_tb.TextWrapping = TextWrapping.Wrap;
                                
            //    TextBlock violatingContext_tb = new TextBlock();
            //    violatingContext_tb.Text = violatingContext;
            //    //violatingContext_tb.Width = threat_history_lb.Width - 10;
            //    violatingContext_tb.Width = threat_history_lb.Width * 3 / 4 - 10;
            //    violatingContext_tb.TextWrapping = TextWrapping.Wrap;
                                
            //    //rationaleMessageTransition = "PreviousTransmission:" + Environment.NewLine + rationaleMessageTransition;
            //    //rationaleContextTransition = "Unsatisfying context:" + Environment.NewLine + rationaleContextTransition;

            //    //string rationaleMessageTransition_pp = (string)threat.rationales["Transmission:"];
            //    //string rationaleContextTransition = (string)threat.rationales["HContext:"];
            //    string aggStatement = (string)threat.rationales["inference:"];

            //    //string[] rationaleMessageTransition_ = rationaleMessageTransition_pp.Split(',');

            //    //string rationaleMessageTransition = rationaleMessageTransition_pp;

            //    //string rationaleMessageTransition = "";
            //    //int count = 0;
            //    //foreach (string spp in rationaleMessageTransition_)
            //    //{
            //    //    if (spp.Trim().Length > 0 && !spp.Equals("\r") && !spp.Equals("\r\n"))
            //    //    {
            //    //        rationaleMessageTransition = rationaleMessageTransition + spp + ",";
            //    //        if (count == 3)
            //    //        {
            //    //            rationaleMessageTransition = rationaleMessageTransition + "\r\n" + "    ";
            //    //            count = 0;
            //    //        }
            //    //        count = count + 1;
            //    //    }                   
            //    //}

            //    ContentPresenter cp1 = new ContentPresenter();
            //    cp1.Content = "Inference:";
            //    ContentPresenter cp2 = new ContentPresenter();
            //    cp2.Content = "    " + aggStatement;
            //    //ContentPresenter cp3 = new ContentPresenter();
            //    //cp3.Content = "PreviousTransmission:";
            //    //ContentPresenter cp4 = new ContentPresenter();
            //    //cp4.Content = "    " + rationaleMessageTransition;
            //    //ContentPresenter cp5 = new ContentPresenter();
            //    //cp5.Content = "UnsatisfyingContext:";

            //    //TextBlock cp6_tb = new TextBlock();
            //    //cp6_tb.Text = rationaleContextTransition;
            //    //cp6_tb.FontSize = 10;
            //    //cp6_tb.Width = threat_history_lb.Width - ((threat_history_lb.Width * 1 / 3) - 5);
            //    //cp6_tb.TextWrapping = TextWrapping.Wrap;
            //    //ContentPresenter cp6 = new ContentPresenter();
            //    //cp6.Content = cp6_tb;
               
            //    StackPanel spcp = new StackPanel();
            //    spcp.Orientation = System.Windows.Controls.Orientation.Vertical;
            //    spcp.Children.Add(cp1);
            //    spcp.Children.Add(cp2);
            //    //spcp.Children.Add(cp3);
            //    //spcp.Children.Add(cp4);
            //    //spcp.Children.Add(cp5);
            //    //spcp.Children.Add(cp6);
            //    spcp.Background = Brushes.LightYellow;    
                
            //    ////rationale = rationale + Environment.NewLine;
            //    //rationale = rationale + "InferenceViolation" + Environment.NewLine;
            //    //rationale = rationale + aggStatement + Environment.NewLine;
            //    ////rationale = rationale + Environment.NewLine;
            //    //rationale = rationale + "PreviousTransmission:" + Environment.NewLine;
            //    //rationale = rationale + rationaleMessageTransition + Environment.NewLine;
            //    ////rationale = rationale + Environment.NewLine;
            //    //rationale = rationale + "UnsatisfyingContext:" + Environment.NewLine;
            //    //rationale = rationale + rationaleContextTransition + Environment.NewLine;

            //    //TextBlock rationale_tb = new TextBlock();
            //    //rationale_tb.Text = rationale;
            //    //rationale_tb.Width = threat_history_lb.Width - 10;
            //    //rationale_tb.FontSize = 10;
            //    //rationale_tb.TextWrapping = TextWrapping.Wrap;

            //    ContentPresenter no_index_cp = new ContentPresenter();
            //    no_index_cp.Content = index + ".";
            //    index = index + 1;
            //    ContentPresenter transmissionMessage_cp = new ContentPresenter();
            //    transmissionMessage_cp.Content = threatMessageTransition_tb;
            //    ContentPresenter violatedPolicy_cp = new ContentPresenter();
            //    violatedPolicy_cp.Content = violatedPolicy_tb;
            //    ContentPresenter violatingContext_cp = new ContentPresenter();
            //    violatingContext_cp.Content = violatingContext_tb;
            //    ContentPresenter rationale_cp = new ContentPresenter();
            //    //rationale_cp.Content = rationale_tb;
            //    rationale_cp.Content = spcp;
            //    //rationale_cp.Content = ratViewer;

            //    //ContentPresenter violate_image_cp = new ContentPresenter();
            //    //BitmapImage cm_i_image = new BitmapImage();
            //    //cm_i_image.BeginInit();
            //    //Uri cm_i_Uri = new Uri("/PMisuseAn;component/images/Warning.ico", UriKind.RelativeOrAbsolute);
            //    //cm_i_image.UriSource = cm_i_Uri;
            //    //cm_i_image.EndInit();

            //    //Image cm_i_iconImage = new Image();
            //    //cm_i_iconImage.Source = cm_i_image;
            //    //violate_image_cp.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            //    //violate_image_cp.Content = cm_i_iconImage;

            //    no_index_cp.Width = threat_history_lb.Width * 1 / 27;
            //    transmissionMessage_cp.Width = threat_history_lb.Width * 3 / 4 - 13;
            //    violatedPolicy_cp.Width = threat_history_lb.Width * 3 / 4 - 13;
            //    violatingContext_cp.Width = threat_history_lb.Width * 3 / 4 - 13;
            //    rationale_cp.Width = threat_history_lb.Width * 3 / 4 - 41;
            //    //violate_image_cp.Width = 20;

            //    ListBoxItem l = new ListBoxItem();
            //    StackPanel s = new StackPanel();
            //    s.Orientation = System.Windows.Controls.Orientation.Vertical;

            //    //ContentPresenter headerNo = new ContentPresenter();
            //    //headerNo.Content = "NO:";
            //    //headerNo.Width = threat_history_lb.Width * 1 / 8 - 5;

            //    ContentPresenter headerViolatingContext = new ContentPresenter();
            //    headerViolatingContext.Content = "Threatening"+"\r\n"+"Context:";
            //    headerViolatingContext.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    ContentPresenter headerMessageTransfer = new ContentPresenter();
            //    headerMessageTransfer.Content = "Information" + "\r\n" + "Transfer:";
            //    headerMessageTransfer.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    ContentPresenter headerVoilatedPolicy = new ContentPresenter();
            //    headerVoilatedPolicy.Content = "Violated"+"\r\n"+"Policy:";
            //    headerVoilatedPolicy.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    ContentPresenter headerRationale = new ContentPresenter();
            //    headerRationale.Content = "Rationale:";
            //    headerRationale.Width = threat_history_lb.Width * 1 / 6 - 3;

            //    //ListBoxItem l_no = new ListBoxItem();
            //    StackPanel s_super = new StackPanel();

            //    s_super.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    //s_super.Children.Add(headerNo);
            //    s_super.Children.Add(no_index_cp);

            //    //l_no.Content = s_super;
            //    //s.Children.Add(l_no);

            //    ListBoxItem l_v_context = new ListBoxItem();
            //    StackPanel s_v_context = new StackPanel();
            //    s_v_context.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    s_v_context.Children.Add(headerViolatingContext);
            //    s_v_context.Children.Add(violatingContext_cp);
            //    l_v_context.Content = s_v_context;
            //    s.Children.Add(l_v_context);

            //    ListBoxItem l_mess = new ListBoxItem();
            //    StackPanel s_mess = new StackPanel();
            //    s_mess.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    s_mess.Children.Add(headerMessageTransfer);
            //    s_mess.Children.Add(transmissionMessage_cp);
            //    l_mess.Content = s_mess;
            //    s.Children.Add(l_mess);

            //    ListBoxItem l_pol = new ListBoxItem();
            //    StackPanel s_pol = new StackPanel();
            //    s_pol.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    s_pol.Children.Add(headerVoilatedPolicy);
            //    s_pol.Children.Add(violatedPolicy_cp);
            //    l_pol.Content = s_pol;
            //    s.Children.Add(l_pol);

            //    ListBoxItem l_rat = new ListBoxItem();
            //    StackPanel s_rat = new StackPanel();
            //    s_rat.Orientation = System.Windows.Controls.Orientation.Horizontal;
            //    s_rat.Children.Add(headerRationale);
            //    s_rat.Children.Add(rationale_cp);
            //    //s_rat.Children.Add(violate_image_cp);
            //    l_rat.Content = s_rat;
            //    s.Children.Add(l_rat);

            //    s_super.Children.Add(s);

            //    //s_super.Children.Add(violate_image_cp);
            //    s_super.VerticalAlignment = System.Windows.VerticalAlignment.Center;

            //    if (threat_history_lb.Items.Count % 2 == 0)
            //    {
            //        l.Background = Brushes.AliceBlue;
            //    }
            //    l.Tag = threat;
            //    //l.Dispatcher.Invoke(new System.Action(() => l.AddHandler(ListBoxItem.SelectedEvent, new RoutedEventHandler(threatHistoryLBItemSelected))), DispatcherPriority.Normal, null);

            //    //l.Foreground = Brushes.Red;
            //    l.Content = s_super;

            //    this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.Items.Add(l)), DispatcherPriority.Normal, null);
            //    //this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.SelectedIndex = general_context_lb.Items.Count-1), DispatcherPriority.Normal, null);            
            //    this.threat_history_lb.Dispatcher.Invoke(new System.Action(() => this.threat_history_lb.ScrollIntoView(threat_history_lb.Items[threat_history_lb.Items.Count - 1])), DispatcherPriority.Normal, null);

            //    //mitigate threat
            //    mitigationEnforcementSelection(threat, violatingPolicyStatement, threatMessageTransition, violatingContext, rationale);
            //}

            ////////////////////
            ////////////////////////
        }

        //public void threatHistoryLBItemSelected(object sender, RoutedEventArgs e)
        //{
        //    ListBoxItem a_i = (ListBoxItem)sender;
        //    Threat threat = (Threat)a_i.Tag;
        //    if(threat != null)
        //    {
        //        threat.generateMitigationOptions();
        //        possible_mitigation_actions_lb.Items.Clear();

        //        foreach (string m_option in threat.mitigationOptions)
        //        {
        //            CheckBox mitigation_item = new CheckBox();
        //            mitigation_item.FontSize = 10;
        //            mitigation_item.Content = m_option;
        //            mitigation_item.Tag = threat;
        //            mitigation_item.Dispatcher.Invoke(new System.Action(() => mitigation_item.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(mitigationEnforcementSelected))), DispatcherPriority.Normal, null);
               
        //            possible_mitigation_actions_lb.Items.Add(mitigation_item);
        //        }                
        //    }
        //}

        public void mitigationEnforcementSelection(List<Threat> threats,  string violatingPolicyStatement, string threatMessageTransition
                , string violatingContext, string rationale)
        {
            //if (!threat.subjectAgent.agentName.Equals(source_agent_name))
            //    return;

            if (AdaptationMgtConfigWindow.isAdaptationConfigured == false)
            {
                MessageBoxResult resultm = MessageBox.Show(this, "AdaptationR Rules not defined",
                            "Confirm", MessageBoxButton.OK,
                            MessageBoxImage.Information);

                return;
            }
            string adaptationAction = AdaptationStratagy.getAdaptationStratagy(threats);
            
            AdaptationDescriptor ad = new AdaptationDescriptor(threats,
                    AdaptationStratagy.threathenedOperationalAttributes,
                    AdaptationStratagy.adaptationAction,
                    AdaptationStratagy.maxUtilityFunctions,
                    AdaptationStratagy.sensitivity_level_utilitys,
                    AdaptationStratagy.obf_level_utilitys,
                    AdaptationStratagy.sensitivity_level_constant,
                    AdaptationStratagy.obf_level_constant,
                    AdaptationStratagy.decisions,
                    AdaptationStratagy.adaptationRule,
                    AdaptationStratagy.metaAdaptationRule,
                    AdaptationStratagy.threatFrequencys,
                    AdaptationStratagy.h_adaptationActionss);
            
            MisUseAnObjectsDB.writeAdaptationDescription(ad, violatingPolicyStatement, 
                threatMessageTransition, violatingContext, rationale, seqTimeline, 
                threats.ElementAt(0).subjectAgent.agentName);

            AdaptationDescriptorBinding aadb = MisUseAnObjectsDB.getAdaptationProperties(ad, violatingPolicyStatement,
                threatMessageTransition, violatingContext, rationale, seqTimeline,
                threats.ElementAt(0).subjectAgent.agentName);

            List<AdaptationBindingInverse> pptydesc = aadb.getPropertyValues();

            adaptActionDataGrid.ItemsSource = pptydesc;

            //adaptationAction_l.Content = adaptationAction;
        }

        //public void mitigationEnforcementSelected(object sender, RoutedEventArgs e)
        //{
        //    CheckBox a_i = (CheckBox)sender;
        //    Threat threat = (Threat)a_i.Tag;
            
        //    if(AdaptationMgtConfigWindow.isAdaptationConfigured == false)
        //    {
        //        MessageBoxResult resultm = MessageBox.Show(this, "AdaptationR Rules not defined",
        //                    "Confirm", MessageBoxButton.OK,
        //                    MessageBoxImage.Information);

        //        return;
        //    }
        //    string adaptationAction = AdaptationStratagy.getAdaptationStratagy(threat);
        //    adaptationAction_l.Content = adaptationAction;

        //    string instruction_s = (string)a_i.Content;

        //    MessageBoxResult result1 = MessageBox.Show(this, instruction_s,
        //                    "Confirm", MessageBoxButton.YesNo,
        //                    MessageBoxImage.Information);

        //    if (result1 == MessageBoxResult.No)
        //    {
        //        return;
        //    }
            
        //    if(instruction_s.Equals("IGNORE"))
        //    {
        //        if (threat != null)
        //        {
        //            bool found = false;
        //            foreach (Threat threat1 in misuseAnalyser.threats)
        //            {
        //                if (threat.timestamp == threat1.timestamp)
        //                {
        //                    found = true;
        //                    misuseAnalyser.threats.Remove(threat1);
        //                    break;
        //                }
        //            }
        //            if (found)
        //            {
        //                possible_mitigation_actions_lb.Items.Clear();
        //                updateAnalysisThreatHistory(contextInstance.currentParameterisedContextInstances, contextInstance.currentSendReceiveContextAgent);
        //                //playCall();           
        //            }
        //        }
        //    }
            
        //}

        public void updateContextInteractionHistory(List<Object> parameterisedContextInstances_,
            Dictionary<Dictionary<Agent, Agent>, ListDictionary> sendReceiveContextAgent)
        {
            string context_text = "";
            string message_text = "";

            int j = 0;
            int m = 0;
            foreach (Object obj in parameterisedContextInstances_)
            {
                Attribute atte = obj as Attribute;
                if (atte != null)
                {
                    if (atte.activeDomain != null && atte.activeDomain.Count() > 0)
                    {
                        context_text = context_text + atte.name + "=" + atte.activeDomain;
                    }
                    else
                    {
                        context_text = context_text + atte.name + "= ?";
                    }                    
                }
                else
                {
                    GroupFunction gf = obj as GroupFunction;
                    if (gf != null)
                    {
                        string membershipFunction = gf.functionName + "(" + gf.agentName + ", " + gf.groupName + ")";
                        context_text = context_text + membershipFunction;
                    }
                }

                if (j < parameterisedContextInstances_.Count() - 1)
                {
                    context_text = context_text + ", ";
                }
                j = j + 1;

                if (m == 3)
                {
                    context_text = context_text + "\r\n";
                    m = 0;
                }
                else
                {
                    m = m + 1;
                }

            }

            message_text = message_text + sendAgent.agentName + "→[";
            message_text = message_text +subjectAgent.agentName + "(";
            State activeState = null;
            Transition activeTransition = null;

            if (message_s != null)
            {
                activeState = message_s;
                int i = 0;
                if (activeState.activeAction != null)
                {
                    int km = 0;
                    foreach (Attribute att in activeState.activeAction.parameterisedOperationalAttributes)
                    {
                        message_text = message_text + att.name + "=" + att.activeDomain;

                        if (i < activeState.activeAction.parameterisedOperationalAttributes.Count - 1)
                        {
                            message_text = message_text + ",";                            
                        }
                        if (km == 3)
                        {
                            message_text = message_text + "\r\n";
                            km = 0;
                        }
                        km = km + 1;
                        i = i + 1;
                    }
                }
            }
            else if (message_t != null)
            {
                activeTransition = message_t;
                int i = 0;
                if (activeTransition.activeEvent != null)
                {
                    int km = 0;
                    foreach (Attribute att in activeTransition.activeEvent.parameterisedOperationalAttributes)
                    {
                        message_text = message_text + att.name + "=" + att.activeDomain;

                        if (i < activeTransition.activeEvent.parameterisedOperationalAttributes.Count - 1)
                        {
                            message_text = message_text + ",";
                        }
                        i = i + 1;

                        if (km == 3)
                        {
                            message_text = message_text + "\r\n";
                            km = 0;
                        }
                        km = km + 1;
                    }
                }
            }

            message_text = message_text + ")]→" + receiveAgent.agentName;

            if (message_s != null)
            {
                message_text = message_text + "       #:" + message_s.name;
            }
            else if (message_t != null)
            {
                message_text = message_text + "       #:" + message_t.transitionName;
            }
            //Console.WriteLine("CONTEXT");
            //Console.WriteLine(context_text);
            //Console.WriteLine("MESSAGE");
            //Console.WriteLine(message_text);           
            //Console.WriteLine("---------------");

            ListBoxItem l = new ListBoxItem();
            StackPanel s = new StackPanel();
            s.Orientation = System.Windows.Controls.Orientation.Horizontal;

            ContentPresenter c1 = new ContentPresenter();
            c1.Content = int_seq_no + ".";
            int_seq_no = int_seq_no + 1;

            ContentPresenter c2 = new ContentPresenter();

            TextBlock tb = new TextBlock();
            tb.TextWrapping = TextWrapping.Wrap;
            //tb.Width = general_context_lb.Width / 2 - 55;
            tb.Text = context_text;
            c2.Content = tb;

            ContentPresenter c3 = new ContentPresenter();

            TextBlock tb2 = new TextBlock();
            tb2.TextWrapping = TextWrapping.Wrap;
            tb2.Text = message_text;
            //tb2.Width = general_context_lb.Width / 2 - 66;
            c3.Content = tb2;

            ContentPresenter violate_image_cp = new ContentPresenter();
            BitmapImage cm_i_image = new BitmapImage();
            cm_i_image.BeginInit();

            Uri cm_i_Uri = null;
            if (source_agent.agentName.Equals(receiveAgent.agentName))
            {
                cm_i_Uri = new Uri("/PMisuseAn;component/images/DoubleLeftArrow.png", UriKind.RelativeOrAbsolute);
            }
            else if (misuseAnalyser.misuseFound)
            {
                    cm_i_Uri =  new Uri("/PMisuseAn;component/images/Error.ico", UriKind.RelativeOrAbsolute);
            }
            else if (misuseAnalyser.potentialMisuseFound)
            {
                    cm_i_Uri =  new Uri("/PMisuseAn;component/images/Warning.ico", UriKind.RelativeOrAbsolute);
            }
            else
            {
                    cm_i_Uri =  new Uri("/PMisuseAn;component/images/Green.ico", UriKind.RelativeOrAbsolute);
            }
            cm_i_image.UriSource = cm_i_Uri;
            cm_i_image.EndInit();

            Image cm_i_iconImage = new Image();
            cm_i_iconImage.Source = cm_i_image;
            violate_image_cp.Content = cm_i_iconImage;
            
            if (general_context_lb.Items.Count % 2 == 0)
            {
                l.Background = Brushes.AliceBlue;
            }
            ContentPresenter empty = new ContentPresenter();

            c1.Width = 30;
            c2.Width = tabControl3.Width / 2 - 45;
            empty.Width = 15;
            c3.Width = tabControl3.Width / 2 - 60;
            violate_image_cp.Width = 16;
            s.Children.Add(c1);
            s.Children.Add(c2);
            s.Children.Add(empty);
            s.Children.Add(c3);
            s.Children.Add(violate_image_cp);

            l.Content = s;


            this.general_context_lb.Dispatcher.Invoke(new System.Action(() => this.general_context_lb.Items.Add(l)), DispatcherPriority.Normal, null);
            //this.general_context_lb.Dispatcher.Invoke(new System.Action(() => this.general_context_lb.SelectedIndex = general_context_lb.Items.Count - 1), DispatcherPriority.Normal, null);
            this.general_context_lb.Dispatcher.Invoke(new System.Action(() => this.general_context_lb.ScrollIntoView(general_context_lb.Items[general_context_lb.Items.Count - 1])), DispatcherPriority.Normal, null);
            

            //if (subjectAgent.agentName.Equals(source_agent_name) || receiveAgent.agentName.Equals(source_agent_name))
            //{
            //    ListBoxItem l2= new ListBoxItem();
            //    StackPanel s2 = new StackPanel();
            //    s2.Orientation = System.Windows.Controls.Orientation.Horizontal;

            //    ContentPresenter c12 = new ContentPresenter();
            //    c12.Content = int_seq_no_specific + ".";
            //    int_seq_no_specific = int_seq_no_specific + 1;

            //    ContentPresenter c22 = new ContentPresenter();

            //    TextBlock tbx = new TextBlock();
            //    tbx.TextWrapping = TextWrapping.Wrap;
            //    tbx.Text = context_text;
            //    c22.Content = tbx;

            //    ContentPresenter c32 = new ContentPresenter();

            //    TextBlock tb22 = new TextBlock();
            //    tb22.TextWrapping = TextWrapping.Wrap;
            //    tb22.Text = message_text;
            //    c32.Content = tb22;

            //    if (specific_context_lb.Items.Count % 2 == 0)
            //    {
            //        l2.Background = Brushes.AliceBlue;
            //    }
            //    ContentPresenter empty2 = new ContentPresenter();

            //    c12.Width = 30;
            //    c22.Width = specific_context_lb.Width / 2 - 45;
            //    empty2.Width = 15;
            //    c32.Width = specific_context_lb.Width / 2 - 60;
            //    s2.Children.Add(c12);
            //    s2.Children.Add(c22);
            //    s2.Children.Add(empty2);
            //    s2.Children.Add(c32);

            //    l2.Content = s2;


            //    this.specific_context_lb.Dispatcher.Invoke(new System.Action(() => this.specific_context_lb.Items.Add(l2)), DispatcherPriority.Normal, null);
            //    //this.specific_context_lb.Dispatcher.Invoke(new System.Action(() => this.specific_context_lb.SelectedIndex = specific_context_lb.Items.Count - 1), DispatcherPriority.Normal, null);
            //    this.specific_context_lb.Dispatcher.Invoke(new System.Action(() => this.specific_context_lb.ScrollIntoView(specific_context_lb.Items[specific_context_lb.Items.Count - 1])), DispatcherPriority.Normal, null);
            //}

            if (sendAgent.agentName.Equals(source_agent_name) || subjectAgent.agentName.Equals(source_agent_name) || receiveAgent.agentName.Equals(source_agent_name))
            {
                ListBoxItem l2 = new ListBoxItem();
                StackPanel s2 = new StackPanel();
                s2.Orientation = System.Windows.Controls.Orientation.Horizontal;

                ContentPresenter c12 = new ContentPresenter();
                c12.Content = int_seq_no_specific + ".";
                int_seq_no_specific = int_seq_no_specific + 1;

                ContentPresenter c22 = new ContentPresenter();

                TextBlock tbx = new TextBlock();
                tbx.TextWrapping = TextWrapping.Wrap;
                tbx.Text = context_text;
                c22.Content = tbx;

                ContentPresenter c32 = new ContentPresenter();

                TextBlock tb22 = new TextBlock();
                tb22.TextWrapping = TextWrapping.Wrap;
                tb22.Text = message_text;
                c32.Content = tb22;

                ContentPresenter violate_image_cpx = new ContentPresenter();
                BitmapImage cm_i_imagex = new BitmapImage();
                cm_i_imagex.BeginInit();
                Uri cm_i_Urix = null;
                if (source_agent.agentName.Equals(receiveAgent.agentName))
                {
                    cm_i_Urix = new Uri("/PMisuseAn;component/images/DoubleLeftArrow.png", UriKind.RelativeOrAbsolute);
                }
                else if (misuseAnalyser.misuseFound)
                {
                     cm_i_Urix =  new Uri("/PMisuseAn;component/images/Error.ico", UriKind.RelativeOrAbsolute);
                }
                else if (misuseAnalyser.potentialMisuseFound)
                {
                     cm_i_Urix =  new Uri("/PMisuseAn;component/images/Warning.ico", UriKind.RelativeOrAbsolute);
                }
                else
                {
                     cm_i_Urix =  new Uri("/PMisuseAn;component/images/Green.ico", UriKind.RelativeOrAbsolute);
                }
                cm_i_imagex.UriSource = cm_i_Urix;
                cm_i_imagex.EndInit();

                Image cm_i_iconImagex = new Image();
                cm_i_iconImagex.Source = cm_i_imagex;
                violate_image_cpx.Content = cm_i_iconImagex;
                
                if (specific_lb_1.Items.Count % 2 == 0)
                {
                    l2.Background = Brushes.AliceBlue;
                }
                ContentPresenter empty2 = new ContentPresenter();

                c12.Width = 30;
                c22.Width = tabControl3.Width / 2 - 45;
                empty2.Width = 15;
                c32.Width = tabControl3.Width / 2 - 60;
                violate_image_cpx.Width = 16;
                s2.Children.Add(c12);
                s2.Children.Add(c22);
                s2.Children.Add(empty2);
                s2.Children.Add(c32);
                s2.Children.Add(violate_image_cpx);

                l2.Content = s2;
                
                this.specific_lb_1.Dispatcher.Invoke(new System.Action(() => this.specific_lb_1.Items.Add(l2)), DispatcherPriority.Normal, null);
                //this.specific_lb_1.Dispatcher.Invoke(new System.Action(() => this.specific_lb_1.SelectedIndex = specific_context_lb.Items.Count - 1), DispatcherPriority.Normal, null);
                this.specific_lb_1.Dispatcher.Invoke(new System.Action(() => this.specific_lb_1.ScrollIntoView(specific_lb_1.Items[specific_lb_1.Items.Count - 1])), DispatcherPriority.Normal, null);
            }
        
        }
        
        public void agentGraphRedraw()
        {
            if (this.agentGraphChanged != null)
            {
                this.agentGraphChanged(this, new EventArgs());
            }
        }
        public void loadAllAgents_cb()
        {
            agentNames = MisUseAnObjectsDB.loadAllAgentNames(MainWindow.clusterName);
            agent_names_cb.ItemsSource = agentNames;
        }
        
       public Graph CreateFSMGraph()
        {
            sourceMachineStartState = MisUseAnObjectsDB.getStartState(source_agent.assignedMachine.machineName, MainWindow.clusterName);
            sourceMachineEndState = MisUseAnObjectsDB.getEndState(source_agent.assignedMachine.machineName, MainWindow.clusterName);

            // Create an FSM graph.
            Graph fsm = new Graph();

            foreach (State s in source_agent.assignedMachine.states)
            {
                Node node = new Node(s.name);
                if (sourceMachineStartState != null && s.name.Equals(sourceMachineStartState))
                {
                    node.Attr.Shape = Microsoft.Msagl.Drawing.Shape.DoubleCircle;
                    node.Attr.AddStyle(Microsoft.Msagl.Drawing.Style.Rounded);
                }
                else if (sourceMachineEndState !=  null && s.name.Equals(sourceMachineEndState))
                {
                    node.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Circle;
                    //node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.Gray;
                    node.Attr.AddStyle(Microsoft.Msagl.Drawing.Style.Bold);
                    node.Attr.AddStyle(Microsoft.Msagl.Drawing.Style.Dashed);

                }
                else
                {
                    
                    node.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Circle;
                }
                fsm.AddNode(node);
            }

            foreach (Transition t in source_agent.assignedMachine.transitions)
            {
                string desc = t.transitionName + "(" + t.associatedEevent + ")";
                fsm.AddEdge(t.startState, desc, t.endState);
            }            

            return fsm;
        }

        string genNodeID(Graph graph)
        {
            int id = 0;
            foreach (DictionaryEntry entry in graph.NodeMap)
            {
                string key = (string)entry.Key;
                string id_s = "" + id;
                if (key.Equals(id_s))
                {
                    id = id + 1;
                }
            }
            return "" + id;

        }

       public bool edgeExist(string source, string sink)
        {
            bool exist = false;
            foreach (Edge edge in agentsGraph.Edges)
            {
                Node node_source = edge.SourceNode;
                Node node_sink = edge.TargetNode;

                if (node_source.Id.Equals(source) && node_sink.Id.Equals(sink))
                {
                    exist = true;
                    break;
                }
            }
            return exist;
        }

        void genAgentsGraph()
        {
            InitializeComponent();
            
            if (source_agent == null)
            {
                genStateMachineGraph(source_agent_name);
            }
            agentNamesInGroup = MisUseAnObjectsDB.loadAgentsInGroupDB(source_agent.associatedGroups, MainWindow.clusterName);

            if (agentsGraph == null)
            {
                agentsGraph = new Graph("ANet");
            }
                        

            if (stopCall == false)
            {
                Hashtable agentNodes = agentsGraph.NodeMap;
                ICollection<Edge> agentAdges = agentsGraph.Edges;
                                
                //clear all node colours
                foreach (DictionaryEntry entry in agentNodes)
                {
                    Node n = (Node)entry.Value;
                    n.Attr.FillColor = Microsoft.Msagl.Drawing.Color.White;
                }

                //add/update send agent node
                Node sendAgent_node = null;
                foreach (DictionaryEntry entry in agentNodes)
                {
                    Node n = (Node)entry.Value;
                    if (n.Id.Equals(sendAgent.agentName))
                    {
                        sendAgent_node = n;
                        break;
                    }
                }
                if (sendAgent_node == null)
                {
                    sendAgent_node = new Node(sendAgent.agentName);
                    sendAgent_node.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Circle;
                    agentsGraph.AddNode(sendAgent_node);
                }
                sendAgent_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.DarkOrange;

                //add/unpdate receive agent node
                Node receiveAgent_node = null;
                foreach (DictionaryEntry entry in agentNodes)
                {
                    Node n = (Node)entry.Value;
                    if (n.Id.Equals(receiveAgent.agentName))
                    {
                        receiveAgent_node = n;
                        break;
                    }
                }
                if (receiveAgent_node == null)
                {
                    receiveAgent_node = new Node(receiveAgent.agentName);
                    receiveAgent_node.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Circle;
                    agentsGraph.AddNode(receiveAgent_node);
                }
                receiveAgent_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.DarkOrange;
                
                //update color of source agent
                string sourceAgentKey = "";
                foreach (DictionaryEntry entry in agentsGraph.NodeMap)
                {
                    Node n = (Node)entry.Value;
                    if (n.Attr.Id.Equals(source_agent_name))
                    {
                        sourceAgentKey = (string)entry.Key;
                        break;
                    }
                }

                Node sourceAgentNode = agentsGraph.FindNode(sourceAgentKey);
                if (sourceAgentNode != null)
                {
                    sourceAgentNode.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightBlue;
                }

                //update color of subject agent
                if (!(subjectAgent.agentName.Equals(sendAgent.agentName)) && !(subjectAgent.agentName.Equals(receiveAgent.agentName)))
                {
                    string subjectAgentKey = "";
                    foreach (DictionaryEntry entry in agentsGraph.NodeMap)
                    {
                        Node n = (Node)entry.Value;
                        if (n.Attr.Id.Equals(subjectAgent.agentName))
                        {
                            subjectAgentKey = (string)entry.Key;
                            break;
                        }
                    }

                    Node subjectAgentNode = agentsGraph.FindNode(subjectAgentKey);
                    if (subjectAgentNode != null)
                    {
                        subjectAgentNode.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightYellow;
                    }
                }                

                //clear all edge colours
                foreach (Edge edge in agentAdges)
                {
                   edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Black;
                }

                //delete sendreceive edge if exist
                Edge activeEdge = null;
                foreach (Edge edge in agentAdges)
                {
                    string sourceNode = edge.Source;
                    string endNode = edge.Target;
                    if (sourceNode.Equals(sendAgent.agentName) && endNode.Equals(receiveAgent.agentName))
                    {
                        activeEdge = edge;
                        break;
                    }
                }
                if(activeEdge != null)
                    agentsGraph.Edges.Remove(activeEdge);

                //add/update edge between receive and send agent
                Edge send_receive_edge = null;
                foreach (Edge edge in agentAdges)
                {
                    if (edge.Source == sendAgent_node.Id && edge.Target == receiveAgent_node.Id)
                    {
                        send_receive_edge = edge;
                        break;
                    }
                }
                if (send_receive_edge == null)
                {
                    string edge_desc = "";
                    edge_desc = edge_desc + subjectAgent.agentName + "[";

                    State activeState = null;
                    Transition activeTransition = null;

                    if (message_s != null)
                    {
                        activeState = message_s;
                        int i = 0;
                        if (activeState.activeAction != null)
                        {
                            foreach (Attribute att in activeState.activeAction.parameterisedOperationalAttributes)
                            {
                                edge_desc = edge_desc + att.name + "=" + att.activeDomain;

                                if (i < activeState.activeAction.parameterisedOperationalAttributes.Count - 1)
                                {
                                    edge_desc = edge_desc + ",";
                                }
                                i = i + 1;
                            }
                        } 
                    }
                    else if (message_t != null)
                    {
                        activeTransition = message_t;
                        int i = 0;
                        if (activeTransition.activeEvent != null)
                        {
                            foreach (Attribute att in activeTransition.activeEvent.parameterisedOperationalAttributes)
                            {
                                edge_desc = edge_desc + att.name + "=" + att.activeDomain;

                                if (i < activeTransition.activeEvent.parameterisedOperationalAttributes.Count - 1)
                                {
                                    edge_desc = edge_desc + ",";
                                }
                                i = i + 1;
                            }
                        }
                    }
                    edge_desc = edge_desc + "]";
                    //temp removal of edge label for debugging
                    //send_receive_edge = new Edge(sendAgent_node.Id, edge_desc, receiveAgent_node.Id);
                    send_receive_edge = new Edge(sendAgent_node.Id, "", receiveAgent_node.Id);
                    agentsGraph.Edges.Add(send_receive_edge);
                }
                send_receive_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.DarkOrange;

            }
            
            //display agent graph
            agentsGraph.Attr.LayerDirection = LayerDirection.None;
            agentsGraph.Attr.AspectRatio = 1.5;

            //agentsGraph.LayoutAlgorithmSettings = new Microsoft.Msagl.Mds.MdsLayoutSettings();            
            agents_viewer = new GViewer();
            //agents_viewer.CurrentLayoutMethod = Microsoft.Msagl.GraphViewerGdi.LayoutMethod.UseSettingsOfTheGraph;            
            agents_viewer.Graph = agentsGraph;
            agents_viewer.BackColor = System.Drawing.Color.White;
            agents_viewer.Dock = System.Windows.Forms.DockStyle.Fill;

            agents_wfh.Background = Brushes.White;
            //agents_wfh.Child = agents_viewer;
            this.agents_wfh.Dispatcher.Invoke(new System.Action(() => this.agents_wfh.Child = agents_viewer), DispatcherPriority.Normal, null);


            //update stateMachine graph
            Hashtable smNodes = glee_fsm_graph.NodeMap;
            ICollection<Edge> smAdges = glee_fsm_graph.Edges;
            if (contextInstance != null && (HistorySerialisationEngine.totalInteractions() == 1 || subjectAgent.agentName.Equals(source_agent_name) || receiveAgent.agentName.Equals(source_agent_name)))
            {
                //clear all sm node colours
                foreach (DictionaryEntry entry in smNodes)
                {
                    Node n = (Node)entry.Value;
                    n.Attr.FillColor = Microsoft.Msagl.Drawing.Color.White;
                }
                //clear all edge colours
                foreach (Edge edge in smAdges)
                {
                    edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Black;
                }
            }

            if (sendAgent.agentName.Equals(source_agent_name) || subjectAgent.agentName.Equals(source_agent_name) || receiveAgent.agentName.Equals(source_agent_name))
            {
                if (message_s != null)
                {

                    State activeState = message_s;
                    foreach (DictionaryEntry entry in smNodes)
                    {
                        Node n = (Node)entry.Value;
                        if (n.Id.Equals(activeState.name))
                        {
                            n.Attr.FillColor = Microsoft.Msagl.Drawing.Color.DarkOrange;
                            break;
                        }
                    }
                }
                else if (message_t != null)
                {
                    Transition activeTransition = message_t;

                    foreach (Edge edge in smAdges)
                    {
                        if (edge.Source == activeTransition.startState && edge.Target == activeTransition.endState)
                        {
                            edge.Attr.Color = Microsoft.Msagl.Drawing.Color.DarkOrange;
                            break;
                        }
                    }
                }                
            }

            //display sm graph
            fsm_viewer = new GViewer();
            fsm_viewer.Graph = glee_fsm_graph;
            fsm_viewer.BackColor = System.Drawing.Color.White;
            fsm_viewer.Dock = System.Windows.Forms.DockStyle.Fill;

            //this.fsm_wfh.Child = fsm_viewer;
            this.fsm_wfh.Dispatcher.Invoke(new System.Action(() => this.fsm_wfh.Child = fsm_viewer), DispatcherPriority.Normal, null);

        }
        
        public void genStateMachineGraph(string sourceAgentName)
        {
            InitializeComponent();
            if (stopCall == true)
            {
                glee_fsm_graph = new Graph();

            }
            else
            {
                //source_agent = MisUseAnObjectsDB.loadGroupAgentDBAgent(sourceAgentName, MainWindow.clusterName);
                source_agent = MisUseAnObjectsDB.loadAgentDB(sourceAgentName, MainWindow.clusterName);
                //string label_content = "ownes(machine[" + source_agent.assignedMachine.machineName + "] ";
                //label_content = label_content + " inGroup[";
                //int j = 1;
                //foreach (string gm in source_agent.associatedGroups)
                //{
                //    label_content = label_content + gm;
                //    if (j < source_agent.associatedGroups.Count())
                //    {
                //        label_content = label_content + ", ";
                //    }
                //    j = j + 1;
                //}
                //label_content = label_content + "])";
                //agent_mc_g_label.Content = label_content;

                //Serialize(fsm);
                glee_fsm_graph = CreateFSMGraph();

                glee_fsm_graph.Attr.LayerDirection = LayerDirection.None;
                glee_fsm_graph.Attr.AspectRatio = 1.7;

                Hashtable nodes = glee_fsm_graph.NodeMap;
                ICollection<Edge> edges = glee_fsm_graph.Edges;

                //display every other node with in or out nodes
                foreach (Transition t in source_agent.assignedMachine.transitions)
                {
                    if (t.isMisusePoint == true)
                    {
                        MitigationReferences m_ref = MisUseAnObjectsDB.
                        loadTransitionMitigationReferencesDB(t.transitionName, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                        if (m_ref.isEmpty == true)
                        {
                            int index = 0;
                            foreach (Edge edge in edges)
                            {
                                string[] l_s = edge.LabelText.Split('(');
                                string t_label_n = l_s[0];
                                if (t_label_n.Equals(t.transitionName))
                                {
                                    Edge e_n = glee_fsm_graph.Edges.ElementAt(index);
                                    if (e_n != null)
                                    {
                                        e_n.Attr.Color = Microsoft.Msagl.Drawing.Color.OrangeRed;
                                    }
                                }
                                index = index + 1;
                            }
                        }
                        else
                        {
                            string t_sourceNode_key = null;
                            string t_endNode_key = null;
                            string t_endNode_final_key = null;

                            //remove misuse edge
                            foreach (DictionaryEntry entry in nodes)
                            {
                                Node n = (Node)entry.Value;
                                
                                if (n.LabelText.Equals(t.startState))
                                {
                                    t_sourceNode_key = (string)entry.Key;
                                }
                                else if (n.LabelText.Equals(t.endState))
                                {
                                    t_endNode_key = (string)entry.Key;
                                    t_endNode_final_key = (string)entry.Key;
                                }
                                //if(t_sourceNode_key != null && t_endNode_key != null)
                                //{
                                //    break;
                                //}
                            }

                            if (t_sourceNode_key != null && t_endNode_key != null)
                            {
                                Edge t_edge = null;
                                foreach (Edge edge in edges)
                                {
                                    if (edge.Source == t_sourceNode_key && edge.Target == t_endNode_key)
                                    {
                                        t_edge = edge;
                                        break;
                                    }
                                }
                                glee_fsm_graph.Edges.Remove(t_edge);

                                //add mitigation edges (mitigation transitions)                            
                                var mitigation_trans = new Dictionary<Transition, int>();
                                foreach (Transition trans in m_ref.transitions)
                                {
                                    mitigation_trans.Add(trans, trans.mitigationSeqRefIndex);
                                }

                                var ordered_mitigation_trans = from k in mitigation_trans.Keys
                                                               orderby mitigation_trans[k] ascending
                                                               select k;

                                Edge t_mmu_edge = null;
                                string desc_t_mmu = null;
                                int mit_no = 1;
                                string t_mr_sourceNode_key = null;
                                string t_mr_endNode_key = null;

                                if (m_ref.transitions.Count() == 0)
                                {
                                    t_mr_endNode_key = t_sourceNode_key;
                                }

                                for (int i = 0; i < ordered_mitigation_trans.Count(); i++)
                                {
                                    Transition t_mr = ordered_mitigation_trans.ElementAt(i);

                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;
                                        if (n.LabelText.Equals(t_mr.startState))
                                        {
                                            t_mr_sourceNode_key = (string)entry.Key;
                                        }
                                        else if (n.LabelText.Equals(t_mr.endState))
                                        {
                                            t_mr_endNode_key = (string)entry.Key;
                                        }
                                        //if (t_mr_sourceNode_key != null && t_mr_endNode_key != null)
                                        //{
                                        //    break;
                                        //}
                                    }

                                    if (t_mr_sourceNode_key == null)
                                    {
                                        t_mr_sourceNode_key = genNodeID(glee_fsm_graph);
                                        glee_fsm_graph.NodeMap.Add(t_mr_sourceNode_key, t_mr.startState);
                                    }
                                    if (t_mr_endNode_key == null)
                                    {
                                        t_mr_endNode_key = genNodeID(glee_fsm_graph);
                                        glee_fsm_graph.NodeMap.Add(t_mr_endNode_key, t_mr.endState);
                                    }

                                    string desc_t_mmu_mit = t.transitionName + "[MITIGATED][" + mit_no + "]";
                                    mit_no = mit_no + 1;
                                    Edge t_mmu_mit_edge = null;
                                    t_mmu_mit_edge = new Edge(t_sourceNode_key, desc_t_mmu_mit, t_mr_sourceNode_key);
                                    t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mmu_mit_edge);

                                    string desc_t_mr = t_mr.transitionName + "(" + t_mr.associatedEevent + ")[" + mit_no + "]";
                                    mit_no = mit_no + 1;
                                    Edge t_mr_edge = null;
                                    t_mr_edge = new Edge(t_mr_sourceNode_key, desc_t_mr, t_mr_endNode_key);
                                    t_mr_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mr_edge);

                                    if (ordered_mitigation_trans.Count() > (i + 1))
                                    {
                                        Transition trans_next = ordered_mitigation_trans.ElementAt(i + 1);

                                        foreach (DictionaryEntry entry in nodes)
                                        {
                                            Node n = (Node)entry.Value;

                                            if (n.LabelText.Equals(t_mr.startState))
                                            {
                                                t_mr_sourceNode_key = (string)entry.Key;
                                            }
                                            else if (n.LabelText.Equals(t_mr.endState))
                                            {
                                                t_mr_endNode_key = (string)entry.Key;
                                            }

                                            if (n.Equals(trans_next.startState))
                                            {
                                                t_endNode_key = (string)entry.Key;
                                            }
                                        }
                                        t_sourceNode_key = t_mr_endNode_key;
                                    }
                                    else
                                    {
                                        desc_t_mmu = t.transitionName + "(" + t.associatedEevent + ")[" + mit_no + "]";

                                    }

                                }

                                //add mitigation nodes (mitigation states)
                                var mitigation_states = new Dictionary<State, int>();
                                foreach (State state in m_ref.states)
                                {
                                    mitigation_states.Add(state, state.mitigationSeqRefIndex);
                                }

                                var ordered_mitigation_states = from k in mitigation_states.Keys
                                                                orderby mitigation_states[k] ascending
                                                                select k;

                                for (int i = 0; i < ordered_mitigation_states.Count(); i++)
                                {
                                    State s_mr = ordered_mitigation_states.ElementAt(i);

                                    string s_mr_node_key = null;
                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;
                                        if (n.LabelText.Equals(s_mr.name))
                                        {
                                            s_mr_node_key = (string)entry.Key;
                                            break;
                                        }
                                    }
                                    Node s_nr_node = null;
                                    if (s_mr_node_key != null)
                                    {
                                        s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                        s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                        Edge edge_s_m = new Edge(t_mr_endNode_key, "[M:" + s_mr.name + "]", s_mr_node_key);
                                        edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(edge_s_m);

                                        t_mr_endNode_key = s_mr_node_key;
                                    }
                                }

                                desc_t_mmu = "M:" + t.transitionName + "(" + t.associatedEevent + ")[" + mit_no + "]";
                                t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                glee_fsm_graph.Edges.Add(t_mmu_edge);


                                //add mitigation actions

                                for (int i = 0; i < m_ref.actions.Count(); i++)
                                {
                                    PMisuseAn.behaviour.model.Action s_a_mr = m_ref.actions.ElementAt(i);

                                    String s_mr_name = s_a_mr.stateName;
                                    string s_mr_node_key = null;
                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;
                                        if (n.LabelText.Equals(s_mr_name))
                                        {
                                            s_mr_node_key = (string)entry.Key;
                                            break;
                                        }
                                    }
                                    Node s_nr_node = null;
                                    if (s_mr_node_key != null)
                                    {
                                        s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                        s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                        Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr_name + "]ACT", s_mr_node_key);
                                        edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(edge_s_m);

                                        t_mr_endNode_key = s_mr_node_key;
                                    }
                                }
                            }
                        }
                    }
                }


                foreach (State s in source_agent.assignedMachine.states)
                {
                    if (s.isMisusePoint == true)
                    {
                        MitigationReferences m_ref = MisUseAnObjectsDB.
                                            loadStateMitigationReferencesDB(s.name, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                        Node s_node = null;
                        string s_node_key = null;

                        string t_endNode_final_key = null;

                        foreach (DictionaryEntry entry in nodes)
                        {
                            Node n = (Node)entry.Value;
                            if (n.LabelText.Equals(s.name))
                            {
                                s_node_key = (string)entry.Key;
                                t_endNode_final_key = s_node_key;
                                break;
                            }
                        }
                        s_node = glee_fsm_graph.FindNode(s_node_key);

                        if (s_node != null && m_ref.isEmpty == true)
                        {
                            s_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.OrangeRed;
                        }

                        else if (s_node != null && m_ref.isEmpty == false)
                        {
                            //add mitigation edges (mitigation transitions)                            
                            var mitigation_trans = new Dictionary<Transition, int>();
                            foreach (Transition trans in m_ref.transitions)
                            {
                                mitigation_trans.Add(trans, trans.mitigationSeqRefIndex);
                            }

                            var ordered_mitigation_trans = from k in mitigation_trans.Keys
                                                           orderby mitigation_trans[k] ascending
                                                           select k;

                            int mit_no = 1;
                            string t_mr_sourceNode_key = null;
                            string t_mr_endNode_key = null;

                            IEnumerable<Edge> _s_in_edges = s_node.InEdges;
                            IEnumerable<Edge> _s_self_edges = s_node.SelfEdges;

                            if (_s_in_edges.Count() == 0 && _s_self_edges.Count() == 0)
                            {
                                string last_t_mr_endNode_key = null;
                                Edge t_mmu_edge = null;

                                for (int i = 0; i < ordered_mitigation_trans.Count(); i++)
                                {
                                    Transition t_mr = ordered_mitigation_trans.ElementAt(i);

                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;

                                        if (n.LabelText.Equals(t_mr.startState))
                                        {
                                            t_mr_sourceNode_key = (string)entry.Key;
                                        }
                                        else if (n.LabelText.Equals(t_mr.endState))
                                        {
                                            t_mr_endNode_key = (string)entry.Key;
                                        }
                                        //if (t_mr_sourceNode_key != null && t_mr_endNode_key != null)
                                        //{
                                        //    break;
                                        //}
                                    }
                                    if (t_mr_sourceNode_key == null)
                                    {
                                        t_mr_sourceNode_key = genNodeID(glee_fsm_graph);
                                        glee_fsm_graph.NodeMap.Add(t_mr_sourceNode_key, t_mr.startState);
                                    }
                                    if (t_mr_endNode_key == null)
                                    {
                                        t_mr_endNode_key = genNodeID(glee_fsm_graph);
                                        glee_fsm_graph.NodeMap.Add(t_mr_endNode_key, t_mr.endState);
                                    }
                                    if (last_t_mr_endNode_key != null)
                                    {
                                        string last_desc_t_mmu_mit = "T[MIT-LINK]";
                                        Edge last_t_mmu_mit_edge = null;
                                        last_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                        last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge);
                                    }
                                    string desc_t_mmu_mit = t_mr.transitionName + "[MITIGATED][" + mit_no + "]";
                                    mit_no = mit_no + 1;
                                    Edge t_mmu_mit_edge = null;
                                    t_mmu_mit_edge = new Edge(t_mr_sourceNode_key, desc_t_mmu_mit, t_mr_endNode_key);
                                    t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mmu_mit_edge);

                                    last_t_mr_endNode_key = t_mr_endNode_key;
                                }

                                if (m_ref.states.Count() == 0 && m_ref.actions.Count() == 0)
                                {
                                    string final_desc_t_mmu_mit = "T[MIT-LINK-F]";
                                    mit_no = mit_no + 1;
                                    Edge final_t_mmu_mit_edge = null;
                                    final_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, final_desc_t_mmu_mit, t_endNode_final_key);
                                    final_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(final_t_mmu_mit_edge);
                                }
                                else
                                {

                                }


                                //add mitigation nodes (mitigation states)
                                var mitigation_states = new Dictionary<State, int>();
                                foreach (State state in m_ref.states)
                                {
                                    mitigation_states.Add(state, state.mitigationSeqRefIndex);
                                }

                                var ordered_mitigation_states = from k in mitigation_states.Keys
                                                                orderby mitigation_states[k] ascending
                                                                select k;

                                for (int i = 0; i < ordered_mitigation_states.Count(); i++)
                                {
                                    State s_mr = ordered_mitigation_states.ElementAt(i);

                                    string s_mr_node_key = null;
                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;
                                        if (n.LabelText.Equals(s_mr.name))
                                        {
                                            s_mr_node_key = (string)entry.Key;
                                            break;
                                        }
                                    }
                                    Node s_nr_node = null;
                                    if (s_mr_node_key != null)
                                    {
                                        s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                        s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                        // Edge edge_s_m = new Edge(t_mr_endNode_key, "[M:" + s_mr.name + "]", s_mr_node_key);

                                        Edge edge_s_m = null;
                                        if (m_ref.states.Count() > 0 && t_mr_endNode_key != null)
                                        {
                                            edge_s_m = new Edge(t_mr_endNode_key, "[M:" + s_mr.name + "]", s_mr_node_key);
                                            edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(edge_s_m);
                                        }
                                        else if (t_mr_endNode_key != null)
                                        {
                                            edge_s_m = new Edge(s_mr_node_key, "[M:" + s_mr.name + "]", t_endNode_final_key);
                                            edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(edge_s_m);
                                        }

                                        //edge_s_m.Attr.Color = Microsoft.Glee.Drawing.Color.Green;
                                        //glee_fsm_graph.Edges.Add(edge_s_m);

                                        t_mr_endNode_key = s_mr_node_key;
                                    }
                                }

                                if (m_ref.states.Count() > 0 && m_ref.actions.Count() == 0)
                                {
                                    string desc_t_mmu = "M:[T-S]";
                                    t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                    t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mmu_edge);
                                }


                                //add mitigation actions

                                for (int i = 0; i < m_ref.actions.Count(); i++)
                                {
                                    PMisuseAn.behaviour.model.Action s_a_mr = m_ref.actions.ElementAt(i);

                                    String s_mr_name = s_a_mr.stateName;
                                    string s_mr_node_key = null;
                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;
                                        if (n.LabelText.Equals(s_mr_name))
                                        {
                                            s_mr_node_key = (string)entry.Key;
                                            break;
                                        }
                                    }
                                    Node s_nr_node = null;
                                    if (s_mr_node_key != null)
                                    {
                                        s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                        s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                        Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr_name + "]ACT", s_mr_node_key);
                                        edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(edge_s_m);

                                        t_mr_endNode_key = s_mr_node_key;
                                    }
                                }

                                if (m_ref.states.Count() > 0 && m_ref.actions.Count > 0)
                                {
                                    string desc_t_mmu = "ACT-M:[T-S]ACT";
                                    t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                    t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mmu_edge);
                                }
                            }
                            else
                            {
                                foreach (Edge s_in_edge in _s_in_edges)
                                {
                                    //remove edge from _s_node
                                    glee_fsm_graph.Edges.Remove(s_in_edge);

                                    //get s_in_edge_keys and recreate new edge link to mitigation ref
                                    string s_in_edge_source_key = s_in_edge.SourceNode.Id;
                                    string s_in_edge_target_key = s_in_edge.TargetNode.Id;
                                    string s_in_edge_label = s_in_edge.LabelText;

                                    string last_t_mr_endNode_key = null;
                                    Edge t_mmu_edge = null;

                                    for (int i = 0; i < ordered_mitigation_trans.Count(); i++)
                                    {
                                        Transition t_mr = ordered_mitigation_trans.ElementAt(i);

                                        foreach (DictionaryEntry entry in nodes)
                                        {
                                            Node n = (Node)entry.Value;

                                            if (n.LabelText.Equals(t_mr.startState))
                                            {
                                                t_mr_sourceNode_key = (string)entry.Key;
                                            }
                                            else if (n.LabelText.Equals(t_mr.endState))
                                            {
                                                t_mr_endNode_key = (string)entry.Key;
                                            }
                                            //if (t_mr_sourceNode_key != null && t_mr_endNode_key != null)
                                            //{
                                            //    break;
                                            //}
                                        }
                                        if (t_mr_sourceNode_key == null)
                                        {
                                            t_mr_sourceNode_key = genNodeID(glee_fsm_graph);
                                            glee_fsm_graph.NodeMap.Add(t_mr_sourceNode_key, t_mr.startState);
                                        }
                                        if (t_mr_endNode_key == null)
                                        {
                                            t_mr_endNode_key = genNodeID(glee_fsm_graph);
                                            glee_fsm_graph.NodeMap.Add(t_mr_endNode_key, t_mr.endState);
                                        }
                                        if (last_t_mr_endNode_key != null)
                                        {
                                            string last_desc_t_mmu_mit = "T[MIT-LINK]";
                                            Edge last_t_mmu_mit_edge = null;
                                            last_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                            last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge);
                                        }
                                        else
                                        {
                                            string last_desc_t_mmu_mit = "T[MIT-LINK]";
                                            Edge last_t_mmu_mit_edge = null;
                                            last_t_mmu_mit_edge = new Edge(s_in_edge_source_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                            last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge);
                                        }
                                        string desc_t_mmu_mit = t_mr.transitionName + "[MITIGATED][" + mit_no + "]";
                                        mit_no = mit_no + 1;
                                        Edge t_mmu_mit_edge = null;
                                        t_mmu_mit_edge = new Edge(t_mr_sourceNode_key, desc_t_mmu_mit, t_mr_endNode_key);
                                        t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(t_mmu_mit_edge);

                                        last_t_mr_endNode_key = t_mr_endNode_key;

                                    }

                                    if (m_ref.states.Count() == 0 && m_ref.actions.Count() == 0)
                                    {
                                        string final_desc_t_mmu_mit = "M:" + s_in_edge_label + "]";
                                        mit_no = mit_no + 1;
                                        Edge final_t_mmu_mit_edge = null;
                                        final_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, final_desc_t_mmu_mit, s_in_edge_target_key);
                                        final_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(final_t_mmu_mit_edge);
                                    }

                                    //add mitigation nodes (mitigation states)
                                    var mitigation_states = new Dictionary<State, int>();
                                    foreach (State state in m_ref.states)
                                    {
                                        mitigation_states.Add(state, state.mitigationSeqRefIndex);
                                    }

                                    var ordered_mitigation_states = from k in mitigation_states.Keys
                                                                    orderby mitigation_states[k] ascending
                                                                    select k;

                                    for (int i = 0; i < ordered_mitigation_states.Count(); i++)
                                    {
                                        State s_mr = ordered_mitigation_states.ElementAt(i);

                                        string s_mr_node_key = null;
                                        foreach (DictionaryEntry entry in nodes)
                                        {
                                            Node n = (Node)entry.Value;
                                            if (n.LabelText.Equals(s_mr.name))
                                            {
                                                s_mr_node_key = (string)entry.Key;
                                                break;
                                            }
                                        }
                                        Node s_nr_node = null;
                                        if (s_mr_node_key != null)
                                        {
                                            s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                            s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                            Edge edge_s_m = null;
                                            if (m_ref.states.Count() > 0 && t_mr_endNode_key != null)
                                            {
                                                edge_s_m = new Edge(t_mr_endNode_key, "[M:" + s_mr.name + "]", s_mr_node_key);
                                                edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                                glee_fsm_graph.Edges.Add(edge_s_m);
                                            }
                                            //else if (t_mr_endNode_key != null)
                                            else
                                            {
                                                edge_s_m = new Edge(s_mr_node_key, "[M:" + s_mr.name + "]", t_endNode_final_key);
                                                edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                                glee_fsm_graph.Edges.Add(edge_s_m);
                                            }

                                            t_mr_endNode_key = s_mr_node_key;
                                        }
                                    }

                                    if (m_ref.states.Count() > 0 && m_ref.transitions.Count() > 0 && m_ref.actions.Count() == 0)
                                    {
                                        //string desc_t_mmu = "M:[T-S]";
                                        string final_desc_t_mmu_mit = "M:" + s_in_edge_label + "]";
                                        t_mmu_edge = new Edge(t_mr_endNode_key, final_desc_t_mmu_mit, t_endNode_final_key);
                                        t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(t_mmu_edge);
                                    }
                                    else if (m_ref.states.Count() > 0 && m_ref.transitions.Count() == 0 && m_ref.actions.Count() == 0)
                                    {
                                        //string desc_t_mmu = "M:[S]";
                                        string final_desc_t_mmu_mit = "M:" + s_in_edge_label + "]";
                                        //t_mmu_edge = new Edge(t_endNode_final_key, final_desc_t_mmu_mit, t_mr_endNode_key);
                                        t_mmu_edge = new Edge(s_in_edge_source_key, final_desc_t_mmu_mit, t_mr_endNode_key);
                                        t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(t_mmu_edge);
                                    }


                                    //add mitigation actions

                                    for (int i = 0; i < m_ref.actions.Count(); i++)
                                    {
                                        PMisuseAn.behaviour.model.Action s_a_mr = m_ref.actions.ElementAt(i);

                                        String s_mr_name = s_a_mr.stateName;
                                        string s_mr_node_key = null;
                                        foreach (DictionaryEntry entry in nodes)
                                        {
                                            Node n = (Node)entry.Value;
                                            if (n.LabelText.Equals(s_mr_name))
                                            {
                                                s_mr_node_key = (string)entry.Key;
                                                break;
                                            }
                                        }
                                        Node s_nr_node = null;
                                        if (s_mr_node_key != null)
                                        {
                                            s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                            s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                            Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr_name + "]ACT", s_mr_node_key);
                                            edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(edge_s_m);

                                            t_mr_endNode_key = s_mr_node_key;
                                        }
                                    }

                                    if (m_ref.states.Count() > 0 && m_ref.actions.Count > 0 && m_ref.transitions.Count > 0)
                                    {
                                        string desc_t_mmu = "ACT-M:[T-S]ACT";
                                        t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                        t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(t_mmu_edge);
                                    }
                                }
                            }

                        }

                    }

                }

                //////////////////////////////////////////

                foreach (State s in source_agent.assignedMachine.states)
                {
                    foreach (PMisuseAn.behaviour.model.Action action in s.actions)
                    {
                        if (action.isMisusePoint == true)
                        {
                            MitigationReferences m_ref = MisUseAnObjectsDB.
                                                loadStateActionMitigationReferencesDB(action.name, s.name, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                            Node s_node = null;
                            string s_node_key = null;

                            string t_endNode_final_key = null;

                            foreach (DictionaryEntry entry in nodes)
                            {
                                Node n = (Node)entry.Value;
                                if (n.LabelText.Equals(s.name))
                                {
                                    s_node_key = (string)entry.Key;
                                    t_endNode_final_key = s_node_key;
                                    break;
                                }
                            }
                            s_node = glee_fsm_graph.FindNode(s_node_key);

                            if (s_node != null && m_ref.isEmpty == true)
                            {
                                s_node.Attr.Color = Microsoft.Msagl.Drawing.Color.OrangeRed;
                            }

                            else if (s_node != null && m_ref.isEmpty == false)
                            {
                                //add mitigation edges (mitigation transitions)                            
                                var mitigation_trans = new Dictionary<Transition, int>();
                                foreach (Transition trans in m_ref.transitions)
                                {
                                    mitigation_trans.Add(trans, trans.mitigationSeqRefIndex);
                                }

                                var ordered_mitigation_trans = from k in mitigation_trans.Keys
                                                               orderby mitigation_trans[k] ascending
                                                               select k;

                                int mit_no = 1;
                                string t_mr_sourceNode_key = null;
                                string t_mr_endNode_key = null;

                                IEnumerable<Edge> _s_in_edges = s_node.InEdges;
                                IEnumerable<Edge> _s_self_edges = s_node.SelfEdges;

                                if (_s_in_edges.Count() == 0 && _s_self_edges.Count() == 0)
                                {
                                    string last_t_mr_endNode_key = null;
                                    Edge t_mmu_edge = null;

                                    for (int i = 0; i < ordered_mitigation_trans.Count(); i++)
                                    {
                                        Transition t_mr = ordered_mitigation_trans.ElementAt(i);

                                        foreach (DictionaryEntry entry in nodes)
                                        {
                                            Node n = (Node)entry.Value;

                                            if (n.LabelText.Equals(t_mr.startState))
                                            {
                                                t_mr_sourceNode_key = (string)entry.Key;
                                            }
                                            else if (n.LabelText.Equals(t_mr.endState))
                                            {
                                                t_mr_endNode_key = (string)entry.Key;
                                            }
                                            //if (t_mr_sourceNode_key != null && t_mr_endNode_key != null)
                                            //{
                                            //    break;
                                            //}
                                        }
                                        if (t_mr_sourceNode_key == null)
                                        {
                                            t_mr_sourceNode_key = genNodeID(glee_fsm_graph);
                                            glee_fsm_graph.NodeMap.Add(t_mr_sourceNode_key, t_mr.startState);
                                        }
                                        if (t_mr_endNode_key == null)
                                        {
                                            t_mr_endNode_key = genNodeID(glee_fsm_graph);
                                            glee_fsm_graph.NodeMap.Add(t_mr_endNode_key, t_mr.endState);
                                        }
                                        if (last_t_mr_endNode_key != null)
                                        {
                                            string last_desc_t_mmu_mit = "T[ACT-MIT-LINK]";
                                            Edge last_t_mmu_mit_edge = null;
                                            last_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                            last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge);
                                        }
                                        string desc_t_mmu_mit = t_mr.transitionName + "[ACT-MITIGATED][" + mit_no + "]";
                                        mit_no = mit_no + 1;
                                        Edge t_mmu_mit_edge = null;
                                        t_mmu_mit_edge = new Edge(t_mr_sourceNode_key, desc_t_mmu_mit, t_mr_endNode_key);
                                        t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(t_mmu_mit_edge);

                                        last_t_mr_endNode_key = t_mr_endNode_key;
                                    }

                                    if (m_ref.states.Count() == 0 && m_ref.actions.Count == 0)
                                    {
                                        string final_desc_t_mmu_mit = "T[ACT-MIT-LINK-F]";
                                        mit_no = mit_no + 1;
                                        Edge final_t_mmu_mit_edge = null;
                                        final_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, final_desc_t_mmu_mit, t_endNode_final_key);
                                        final_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(final_t_mmu_mit_edge);
                                    }
                                    else
                                    {

                                    }


                                    //add mitigation nodes (mitigation states)
                                    var mitigation_states = new Dictionary<State, int>();
                                    foreach (State state in m_ref.states)
                                    {
                                        mitigation_states.Add(state, state.mitigationSeqRefIndex);
                                    }

                                    var ordered_mitigation_states = from k in mitigation_states.Keys
                                                                    orderby mitigation_states[k] ascending
                                                                    select k;

                                    for (int i = 0; i < ordered_mitigation_states.Count(); i++)
                                    {
                                        State s_mr = ordered_mitigation_states.ElementAt(i);

                                        string s_mr_node_key = null;
                                        foreach (DictionaryEntry entry in nodes)
                                        {
                                            Node n = (Node)entry.Value;
                                            if (n.LabelText.Equals(s_mr.name))
                                            {
                                                s_mr_node_key = (string)entry.Key;
                                                break;
                                            }
                                        }
                                        Node s_nr_node = null;
                                        if (s_mr_node_key != null)
                                        {
                                            s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                            s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                            Edge edge_s_m = null;
                                            //if (m_ref.transitions.Count() > 0)
                                            //{
                                            //     edge_s_m = new Edge(t_mr_endNode_key, "[ACT-M:" + s_mr.name + "]", s_mr_node_key);
                                            //}
                                            //else
                                            //{
                                            //    edge_s_m = new Edge(t_endNode_final_key, "[ACT-M:" + s_mr.name + "]", s_mr_node_key);
                                            //}

                                            if (m_ref.states.Count() > 0 && t_mr_endNode_key != null)
                                            {
                                                edge_s_m = new Edge(t_mr_endNode_key, "[ACT-M:" + s_mr.name + "]", s_mr_node_key);
                                                edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                                glee_fsm_graph.Edges.Add(edge_s_m);
                                            }
                                            else if (t_mr_endNode_key != null)
                                            {
                                                edge_s_m = new Edge(s_mr_node_key, "[ACT-M:" + s_mr.name + "]", t_endNode_final_key);
                                                edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                                glee_fsm_graph.Edges.Add(edge_s_m);
                                            }

                                            t_mr_endNode_key = s_mr_node_key;
                                        }
                                    }

                                    if (m_ref.states.Count() > 0 && m_ref.actions.Count == 0)
                                    {
                                        string desc_t_mmu = "ACT-M:[T-S]";
                                        t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                        t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(t_mmu_edge);
                                    }

                                    //add mitigation actions

                                    for (int i = 0; i < m_ref.actions.Count(); i++)
                                    {
                                        PMisuseAn.behaviour.model.Action s_a_mr = m_ref.actions.ElementAt(i);

                                        String s_mr_name = s_a_mr.stateName;
                                        string s_mr_node_key = null;
                                        foreach (DictionaryEntry entry in nodes)
                                        {
                                            Node n = (Node)entry.Value;
                                            if (n.LabelText.Equals(s_mr_name))
                                            {
                                                s_mr_node_key = (string)entry.Key;
                                                break;
                                            }
                                        }
                                        Node s_nr_node = null;
                                        if (s_mr_node_key != null)
                                        {
                                            s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                            s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                            Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr_name + "]ACT", s_mr_node_key);
                                            edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(edge_s_m);

                                            t_mr_endNode_key = s_mr_node_key;
                                        }
                                    }

                                    if (m_ref.states.Count() > 0 && m_ref.actions.Count > 0)
                                    {
                                        string desc_t_mmu = "ACT-M:[T-S]ACT";
                                        t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                        t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(t_mmu_edge);
                                    }
                                }

                                else
                                {
                                    foreach (Edge s_in_edge in _s_in_edges)
                                    {
                                        //remove edge from _s_node
                                        glee_fsm_graph.Edges.Remove(s_in_edge);

                                        //get s_in_edge_keys and recreate new edge link to mitigation ref
                                        string s_in_edge_source_key = s_in_edge.SourceNode.Id;
                                        string s_in_edge_target_key = s_in_edge.TargetNode.Id;

                                        string last_t_mr_endNode_key = null;
                                        Edge t_mmu_edge = null;

                                        for (int i = 0; i < ordered_mitigation_trans.Count(); i++)
                                        {
                                            Transition t_mr = ordered_mitigation_trans.ElementAt(i);

                                            foreach (DictionaryEntry entry in nodes)
                                            {
                                                Node n = (Node)entry.Value;

                                                if (n.LabelText.Equals(t_mr.startState))
                                                {
                                                    t_mr_sourceNode_key = (string)entry.Key;
                                                }
                                                else if (n.LabelText.Equals(t_mr.endState))
                                                {
                                                    t_mr_endNode_key = (string)entry.Key;
                                                }
                                                //if (t_mr_sourceNode_key != null && t_mr_endNode_key != null)
                                                //{
                                                //    break;
                                                //}
                                            }
                                            if (t_mr_sourceNode_key == null)
                                            {
                                                t_mr_sourceNode_key = genNodeID(glee_fsm_graph);
                                                glee_fsm_graph.NodeMap.Add(t_mr_sourceNode_key, t_mr.startState);
                                            }
                                            if (t_mr_endNode_key == null)
                                            {
                                                t_mr_endNode_key = genNodeID(glee_fsm_graph);
                                                glee_fsm_graph.NodeMap.Add(t_mr_endNode_key, t_mr.endState);
                                            }
                                            if (last_t_mr_endNode_key != null)
                                            {
                                                string last_desc_t_mmu_mit = "ACT-T[MIT-LINK]";
                                                Edge last_t_mmu_mit_edge = null;
                                                last_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                                last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                                glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge);
                                            }
                                            else
                                            {
                                                string last_desc_t_mmu_mit = "ACT-T[MIT-LINK]";
                                                Edge last_t_mmu_mit_edge = null;
                                                last_t_mmu_mit_edge = new Edge(s_in_edge_source_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                                last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                                glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge);
                                            }
                                            string desc_t_mmu_mit = t_mr.transitionName + "ACT-[MITIGATED][" + mit_no + "]";
                                            mit_no = mit_no + 1;
                                            Edge t_mmu_mit_edge = null;
                                            t_mmu_mit_edge = new Edge(t_mr_sourceNode_key, desc_t_mmu_mit, t_mr_endNode_key);
                                            t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(t_mmu_mit_edge);

                                            last_t_mr_endNode_key = t_mr_endNode_key;

                                        }

                                        if (m_ref.states.Count() == 0 && m_ref.actions.Count() == 0)
                                        {
                                            string final_desc_t_mmu_mit = "ACT-T[MIT-LINK-F]";
                                            mit_no = mit_no + 1;
                                            Edge final_t_mmu_mit_edge = null;
                                            final_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, final_desc_t_mmu_mit, s_in_edge_target_key);
                                            final_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(final_t_mmu_mit_edge);
                                        }

                                        //add mitigation nodes (mitigation states)
                                        var mitigation_states = new Dictionary<State, int>();
                                        foreach (State state in m_ref.states)
                                        {
                                            mitigation_states.Add(state, state.mitigationSeqRefIndex);
                                        }

                                        var ordered_mitigation_states = from k in mitigation_states.Keys
                                                                        orderby mitigation_states[k] ascending
                                                                        select k;

                                        for (int i = 0; i < ordered_mitigation_states.Count(); i++)
                                        {
                                            State s_mr = ordered_mitigation_states.ElementAt(i);

                                            string s_mr_node_key = null;
                                            foreach (DictionaryEntry entry in nodes)
                                            {
                                                Node n = (Node)entry.Value;
                                                if (n.LabelText.Equals(s_mr.name))
                                                {
                                                    s_mr_node_key = (string)entry.Key;
                                                    break;
                                                }
                                            }
                                            Node s_nr_node = null;
                                            if (s_mr_node_key != null)
                                            {
                                                s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                                s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                                Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr.name + "]", s_mr_node_key);
                                                edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                                glee_fsm_graph.Edges.Add(edge_s_m);

                                                t_mr_endNode_key = s_mr_node_key;
                                            }
                                        }
                                        if (m_ref.states.Count() > 0 && m_ref.actions.Count() == 0)
                                        {
                                            string desc_t_mmu = "ACT-M:[T-S]";
                                            t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                            t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(t_mmu_edge);
                                        }

                                        //add mitigation actions

                                        for (int i = 0; i < m_ref.actions.Count(); i++)
                                        {
                                            PMisuseAn.behaviour.model.Action s_a_mr = m_ref.actions.ElementAt(i);

                                            String s_mr_name = s_a_mr.stateName;
                                            string s_mr_node_key = null;
                                            foreach (DictionaryEntry entry in nodes)
                                            {
                                                Node n = (Node)entry.Value;
                                                if (n.LabelText.Equals(s_mr_name))
                                                {
                                                    s_mr_node_key = (string)entry.Key;
                                                    break;
                                                }
                                            }
                                            Node s_nr_node = null;
                                            if (s_mr_node_key != null)
                                            {
                                                s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                                s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                                Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr_name + "]ACT", s_mr_node_key);
                                                edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                                glee_fsm_graph.Edges.Add(edge_s_m);

                                                t_mr_endNode_key = s_mr_node_key;
                                            }
                                        }

                                        if (m_ref.states.Count() > 0 && m_ref.actions.Count > 0)
                                        {
                                            string desc_t_mmu = "ACT-M:[T-S]ACT";
                                            t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                            t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(t_mmu_edge);
                                        }
                                    }
                                }

                            }

                        }

                    }

                }

                string start_key = "";
                if (sourceMachineStartState != null)
                {
                    foreach (DictionaryEntry entry in nodes)
                    {
                        Node n = (Node)entry.Value;
                        if (n.LabelText.Equals(sourceMachineStartState))
                        {
                            start_key = (string)entry.Key;
                            break;
                        }
                    }

                    Node s_n = glee_fsm_graph.FindNode(start_key);
                    if (s_n != null)
                    {
                        //s_n.Attr.Fillcolor = Microsoft.Glee.Drawing.Color.Green;
                        s_n.Attr.LineWidth = 5;
                    }
                }

                //remove nodes with no in or out edges
                List<string> treatedNodeIds = new List<string>();
                for (int i = 0; i <= glee_fsm_graph.NodeMap.Count + 1; i++)
                {
                    foreach (DictionaryEntry entry in nodes)
                    {
                        Node n = (Node)entry.Value;
                        bool contained = false;
                        foreach (string n_s in treatedNodeIds)
                        {
                            if (n_s.Equals(n.Id))
                            {
                                contained = true;
                            }
                        }
                        if (!contained)
                        {
                            treatedNodeIds.Add(n.Id);

                            if (n.InEdges.Count() == 0 && n.OutEdges.Count() == 0 && n.SelfEdges.Count() == 0)
                            {
                                bool valid_empty_node = true;
                                bool do_v = true;

                                State xstate = source_agent.assignedMachine.getState(n.LabelText);
                                MitigationReferences x_m_refx = MisUseAnObjectsDB.
                                               loadStateMitigationReferencesDB(xstate.name, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                                if (!x_m_refx.isEmpty)
                                {
                                    valid_empty_node = false;
                                }
                                else
                                {

                                X: while (do_v == true)
                                    {
                                        foreach (Transition x_trans in source_agent.assignedMachine.transitions)
                                        {
                                            if (x_trans.isMisusePoint)
                                            {
                                                MitigationReferences x_m_ref = MisUseAnObjectsDB.
                                                    loadTransitionMitigationReferencesDB(x_trans.transitionName, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                                                foreach (State s in x_m_ref.states)
                                                {
                                                    if (s.name.Equals(n.LabelText))
                                                    {
                                                        valid_empty_node = false;
                                                        do_v = false;
                                                        goto X;
                                                    }
                                                }
                                            }
                                        }
                                        foreach (State x_state in source_agent.assignedMachine.states)
                                        {

                                            if (x_state.isMisusePoint)
                                            {
                                                MitigationReferences x_m_ref = MisUseAnObjectsDB.
                                                    loadStateMitigationReferencesDB(x_state.name, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                                                foreach (State s in x_m_ref.states)
                                                {
                                                    if (s.name.Equals(n.LabelText))
                                                    {
                                                        valid_empty_node = false;
                                                        do_v = false;
                                                        goto X;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                foreach (PMisuseAn.behaviour.model.Action x_action in x_state.actions)
                                                {
                                                    if (x_action.isMisusePoint)
                                                    {
                                                        MitigationReferences xa_m_ref = MisUseAnObjectsDB.
                                                    loadStateActionMitigationReferencesDB(x_action.name, x_state.name, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                                                        foreach (State s in xa_m_ref.states)
                                                        {
                                                            if (s.name.Equals(n.LabelText))
                                                            {
                                                                valid_empty_node = false;
                                                                do_v = false;
                                                                goto X;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        do_v = false;
                                    }
                                }

                                if (valid_empty_node == true)
                                {
                                    glee_fsm_graph.NodeMap.Remove(n.Id);
                                }
                                break;
                            }
                        }

                    }
                }

            }//end else for stopCall
           
            //display graph
            fsm_viewer.Graph = glee_fsm_graph;
            fsm_viewer.BackColor = System.Drawing.Color.White;
            fsm_viewer.Dock = System.Windows.Forms.DockStyle.Fill;
            
            this.fsm_wfh.Child = fsm_viewer;
        }
        
        private void agent_names_cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (agent_names_cb.SelectedItem != null)
            {
                source_agent_name = agent_names_cb.SelectedItem.ToString();
            }
            else
            {
                source_agent_name = agent_names_cb.Text;
            }
            sourceAgentName = source_agent_name;

            genStateMachineGraph(source_agent_name);
            //genAgentsGraph(source_agent_name);
            agentIntnet_lab.Visibility = System.Windows.Visibility.Visible;

            //tabControl2.SelectedIndex = 1;

            if (source_agent != null)
            {
                //state machine tab
                loadEvents(source_agent.assignedMachine);
                loadStates(source_agent.assignedMachine);
                loadTransitions(source_agent.assignedMachine);

                state_machine_root.Header = source_agent.agentName+"["+source_agent.assignedMachine.machineName+"]";

                agentAttributes = new List<Attribute>();
                //functionalAttributes = new List<Attribute>();
                environmentalAttributes = new List<Attribute>();

                new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
                new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
                apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
                new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                desc_l.Visibility = System.Windows.Visibility.Hidden;
                update_event_b.Visibility = System.Windows.Visibility.Hidden;
                delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                define_state_b.Visibility = System.Windows.Visibility.Hidden;
                update_state_b.Visibility = System.Windows.Visibility.Hidden;
                delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                start_state_l.Visibility = System.Windows.Visibility.Hidden;
                start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                end_state_l.Visibility = System.Windows.Visibility.Hidden;
                end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                state_machine_tv.Visibility = System.Windows.Visibility.Visible;
                isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
                isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
                
                //knowledge evolution tab
                loadDomainAttributes();
                loadExistingPolicies();
                add_att_b.Dispatcher.Invoke(new System.Action(() => add_att_b.AddHandler(Button.ClickEvent, new RoutedEventHandler(add_att_b_Click))), DispatcherPriority.Normal, null);
                refresh_att_b.Dispatcher.Invoke(new System.Action(() => refresh_att_b.AddHandler(Button.ClickEvent, new RoutedEventHandler(refresh_att_Button_Click))), DispatcherPriority.Normal, null);
                new_policy_b.Dispatcher.Invoke(new System.Action(() => new_policy_b.AddHandler(Button.ClickEvent, new RoutedEventHandler(new_policy_b_Click))), DispatcherPriority.Normal, null);
                new_aggregationrule_b.Dispatcher.Invoke(new System.Action(() => new_aggregationrule_b.AddHandler(Button.ClickEvent, new RoutedEventHandler(new_aggregationrule_b_Click))), DispatcherPriority.Normal, null);
               
                attributes_lb.Visibility = System.Windows.Visibility.Visible;
                add_att_b.Visibility = System.Windows.Visibility.Visible;
                refresh_att_b.Visibility = System.Windows.Visibility.Visible;
                policies_lb.Visibility = System.Windows.Visibility.Visible;
                new_policy_b.Visibility = System.Windows.Visibility.Visible;
                new_aggregationrule_b.Visibility = System.Windows.Visibility.Visible;

            }            
        }
        
        private void loadTransitions(StateMachine machine)
        {
            transitions.Items.Clear();
            TreeViewItem item_n = new TreeViewItem();
            item_n.Header = "New..   ";
            item_n.FontStyle = FontStyles.Italic;
            item_n.Foreground = Brushes.Blue;
            item_n.Tag = "new";
            item_n.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));
            transitions.Items.Add(item_n);

            foreach (Transition trans in machine.transitions)
            {
                string trans_tag = trans.transitionName + "," + trans.machineName + "," + trans.startState +
                    "," + trans.endState + "," + trans.associatedEevent;
                string trans_content = trans.transitionName + "(" + trans.startState +
                    "," + trans.endState + "," + trans.associatedEevent + ")";
                if (!transitions.Items.Contains(trans_content))
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = trans_content;
                    item.Tag = trans_tag;
                    item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));

                    //if (trans.isMitigationPoint == true)
                    //{
                    //    item.Background = Brushes.LightYellow;
                    //}
                    if (trans.isMisusePoint == true)
                    {
                        item.Background = Brushes.OrangeRed;
                    }

                    MitigationReferences m_ref_s = MisUseAnObjectsDB.loadTransitionMitigationReferencesDB(trans.transitionName, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                    if (m_ref_s.isEmpty == false)
                    {
                        item.Background = Brushes.Green;
                    }

                    ContextMenu cm_trans = new System.Windows.Controls.ContextMenu();
                    cm_trans.Height = 60;
                    cm_trans.Width = 150;

                    //MenuItem cm_mp_trans = new MenuItem();
                    //cm_mp_trans.Header = "mitigation point";
                    //cm_mp_trans.Tag = trans_tag;
                    //if (trans.isMitigationPoint == true)
                    //{
                    //    cm_mp_trans.IsChecked = true;
                    //}
                    //cm_mp_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                    //cm_mp_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                    //cm_mp_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    //cm_mp_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    //cm_mp_trans.FontSize = 10;
                    //cm_mp_trans.Background = Brushes.LightYellow;
                    //cm_mp_trans.IsCheckable = true;

                    MenuItem cm_mu_trans = new MenuItem();
                    cm_mu_trans.Header = "misuse point";
                    cm_mu_trans.Tag = trans_tag;
                    if (trans.isMisusePoint == true)
                    {
                        cm_mu_trans.IsChecked = true;
                    }
                    cm_mu_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                    cm_mu_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                    cm_mu_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_mu_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_mu_trans.FontSize = 10;
                    //cm_mu_trans.Background = Brushes.OrangeRed;
                    cm_mu_trans.IsCheckable = true;

                    MenuItem cm_m_mr = new MenuItem();
                    cm_m_mr.Header = "Mitigation references";
                    cm_m_mr.Tag = trans_tag;
                    if (trans.isMisusePoint == false)
                    {
                        cm_m_mr.IsEnabled = false;
                    }
                    if (m_ref_s.isEmpty == false)
                    {
                        cm_m_mr.IsChecked = true;
                    }
                    cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                    cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                    cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_m_mr.FontSize = 10;
                    //cm_m_act.Background = Brushes.OrangeRed;
                    cm_m_mr.IsCheckable = true;

                    //cm_trans.Items.Add(cm_mp_trans);
                    cm_trans.Items.Add(cm_mu_trans);
                    cm_trans.Items.Add(cm_m_mr);

                    item.ContextMenu = cm_trans;

                    transitions.Items.Add(item);
                }
            }
        }

        private void loadTransitions()
        {
            transitions.Items.Clear();
            TreeViewItem item_n = new TreeViewItem();
            item_n.Header = "New..   ";
            item_n.FontStyle = FontStyles.Italic;
            item_n.Foreground = Brushes.Blue;
            item_n.Tag = "new";
            item_n.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));
            transitions.Items.Add(item_n);

            allExistingStateTransitions = MisUseAnObjectsDB.loadAllStateTransitions(source_agent.assignedMachine.machineName, MainWindow.clusterName);
            foreach (Transition trans in allExistingStateTransitions)
            {
                string trans_tag = trans.transitionName + "," + trans.machineName + "," + trans.startState +
                    "," + trans.endState + "," + trans.associatedEevent;
                string trans_content = trans.transitionName + "(" + trans.startState +
                    "," + trans.endState + "," + trans.associatedEevent + ")";
                if (!transitions.Items.Contains(trans_content))
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = trans_content;
                    item.Tag = trans_tag;
                    item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));

                    //if (trans.isMitigationPoint == true)
                    //{
                    //    item.Background = Brushes.LightYellow;
                    //}
                    if (trans.isMisusePoint == true)
                    {
                        item.Background = Brushes.OrangeRed;
                    }

                    MitigationReferences m_ref_s = MisUseAnObjectsDB.loadTransitionMitigationReferencesDB(trans.transitionName, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                    if (m_ref_s.isEmpty == false)
                    {
                        item.Background = Brushes.Green;
                    }

                    ContextMenu cm_trans = new System.Windows.Controls.ContextMenu();
                    cm_trans.Height = 60;
                    cm_trans.Width = 150;

                    //MenuItem cm_mp_trans = new MenuItem();
                    //cm_mp_trans.Header = "mitigation point";
                    //cm_mp_trans.Tag = trans_tag;
                    //if (trans.isMitigationPoint == true)
                    //{
                    //    cm_mp_trans.IsChecked = true;
                    //}
                    //cm_mp_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                    //cm_mp_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                    //cm_mp_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    //cm_mp_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    //cm_mp_trans.FontSize = 10;
                    //cm_mp_trans.Background = Brushes.LightYellow;
                    //cm_mp_trans.IsCheckable = true;

                    MenuItem cm_mu_trans = new MenuItem();
                    cm_mu_trans.Header = "misuse point";
                    cm_mu_trans.Tag = trans_tag;
                    if (trans.isMisusePoint == true)
                    {
                        cm_mu_trans.IsChecked = true;
                    }
                    cm_mu_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                    cm_mu_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                    cm_mu_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_mu_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_mu_trans.FontSize = 10;
                    //cm_mu_trans.Background = Brushes.OrangeRed;
                    cm_mu_trans.IsCheckable = true;

                    MenuItem cm_m_mr = new MenuItem();
                    cm_m_mr.Header = "Mitigation references";
                    cm_m_mr.Tag = trans_tag;
                    if (trans.isMisusePoint == false)
                    {
                        cm_m_mr.IsEnabled = false;
                    }
                    if (m_ref_s.isEmpty == false)
                    {
                        cm_m_mr.IsChecked = true;
                    }
                    cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                    cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                    cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_m_mr.FontSize = 10;
                    //cm_m_act.Background = Brushes.OrangeRed;
                    cm_m_mr.IsCheckable = true;

                    //cm_trans.Items.Add(cm_mp_trans);
                    cm_trans.Items.Add(cm_mu_trans);
                    cm_trans.Items.Add(cm_m_mr);

                    item.ContextMenu = cm_trans;

                    transitions.Items.Add(item);
                }
            }
        }

        private void mitigation_references_transition_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string tag_id = (string)cm_i.Tag;
            string[] tag_comps = tag_id.Split(',');
            string transitionName_t = tag_comps[0];
            string machineName_t = tag_comps[1];
            string startState_t = tag_comps[2];
            string endState_t = tag_comps[3];
            string associatedEvent_t = tag_comps[4];

            if (tag_id != null)
            {
                MitigationReferences m_ref = MisUseAnObjectsDB.
                    loadTransitionMitigationReferencesDB(transitionName_t, machineName_t, MainWindow.clusterName);

                string t_label = transitionName_t + "(" + startState_t + ", " + endState_t + ", " + associatedEvent_t + ")";
                MitigationReferenceWindow mrw = new MitigationReferenceWindow(m_ref, source_agent.assignedMachine.machineName, t_label);
                mrw.Owner = (Window)this.Parent;
                mrw.ShowDialog();

                MisUseAnObjectsDB.addTransitionMitigationReferencesDB(transitionName_t, m_ref, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                loadStates();
                loadTransitions();
                genStateMachineGraph(source_agent.agentName);
            }
        }
        
        private void misuse_point_transition_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string tag_id = (string)cm_i.Tag;
            string[] tag_comps = tag_id.Split(',');
            string transitionName_t = tag_comps[0];
            string machineName_t = tag_comps[1];
            string startState_t = tag_comps[2];
            string endState_t = tag_comps[3];
            string associatedEvent_t = tag_comps[4];

            if (tag_id != null)
            {
                if (cm_i.IsChecked == true)
                {
                    MisUseAnObjectsDB.addTransitionMisusePointDB(transitionName_t, startState_t,
                        endState_t, associatedEvent_t, machineName_t, MainWindow.clusterName);
                }
                else if (cm_i.IsChecked == false)
                {
                    MisUseAnObjectsDB.removeTransitionMisusePointDB(transitionName_t, startState_t,
                        endState_t, associatedEvent_t, machineName_t, MainWindow.clusterName);
                }
                loadTransitions();
                genStateMachineGraph(source_agent.agentName);
            }
        }

        private void transition_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isTransitionSelection = true;

            TreeViewItem d_cb = (TreeViewItem)sender;
            string tag_id = (string)d_cb.Tag;
            reloadEntsInComboBox();

            if (tag_id.Equals("new"))
            {
                newStateTransition = new Transition();
                newStateTransition.machineName = source_agent.assignedMachine.machineName;
                newStateTransition.clusterName = MainWindow.clusterName;
                //isStateTransitionUpdate = false;

                new_ent_name_tb.Text = "";
                new_ent_name_tb.IsReadOnly = false;
                start_state_cb.Text = "";
                start_state_cb.IsEnabled = true;
                end_state_cb.Text = "";
                end_state_cb.IsEnabled = true;
                associated_event_cb.Text = "";
                associated_event_cb.IsEnabled = true;
                loadStateTransitionsPolicyStatementList();

                apply_new_state_transition_b.Visibility = System.Windows.Visibility.Visible;
                update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                string[] tag_comps = tag_id.Split(',');
                string transitionName_t = tag_comps[0];
                string machineName_t = tag_comps[1];
                string startState_t = tag_comps[2];
                string endState_t = tag_comps[3];
                string associatedEvent_t = tag_comps[4];

                newStateTransition = MisUseAnObjectsDB.loadStateTransitionDB(machineName_t,
                    transitionName_t, startState_t, endState_t, associatedEvent_t, MainWindow.clusterName);
                //isStateTransitionUpdate = true;

                new_ent_name_tb.Text = transitionName_t;
                new_ent_name_tb.IsReadOnly = true;
                start_state_cb.Text = startState_t;
                start_state_cb.IsEnabled = false;
                end_state_cb.Text = endState_t;
                end_state_cb.IsEnabled = false;
                associated_event_cb.Text = associatedEvent_t;
                associated_event_cb.IsEnabled = false;
                if (newStateTransition.isCallable)
                {
                    isCallableTransition_cb.IsChecked = true;
                }
                else
                {
                    isCallableTransition_cb.IsChecked = false;
                }
                if (newStateTransition.policyIDs != null)
                    reloadStateTransitionsPolicyStatementList(newStateTransition.policyIDs);

                apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                update_new_state_transition_b.Visibility = System.Windows.Visibility.Visible;
                delete_state_transition_b.Visibility = System.Windows.Visibility.Visible;
            }

            new_ent_name_tb.Visibility = System.Windows.Visibility.Visible;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Visible;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Visible;
            start_state_l.Visibility = System.Windows.Visibility.Visible;
            start_state_cb.Visibility = System.Windows.Visibility.Visible;
            ass_event_l.Visibility = System.Windows.Visibility.Visible;
            associated_event_cb.Visibility = System.Windows.Visibility.Visible;
            end_state_l.Visibility = System.Windows.Visibility.Visible;
            end_state_cb.Visibility = System.Windows.Visibility.Visible;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Visible;
        }

        CheckBox donillcb;
        List<Policy> policy_statements;

        private void loadStateTransitionsPolicyStatementList()
        {
            int stat_no = 1;
            policy_statements = MisUseAnObjectsDB.loadAllPolicyStatementsFull(MainWindow.clusterName);

            if (policy_statements != null)
            {
                transition_policies_lb.Items.Clear();
                
                foreach (Policy p_stat in policy_statements)
                {
                    ListBoxItem l = new ListBoxItem();                    
                    StackPanel s = new StackPanel();
                    s.Orientation = System.Windows.Controls.Orientation.Horizontal;
                    ContentPresenter c1 = new ContentPresenter();
                    c1.Content = stat_no;
                    stat_no = stat_no + 1;
                    
                    CheckBox cb = new CheckBox();
                    cb.Tag = p_stat.id;

                    if (p_stat.statement.Equals("DO[NILL]"))
                    {
                        cb.Content = p_stat.statement;
                        l.Foreground = Brushes.DarkRed;
                        cb.Foreground = Brushes.DarkRed;                    
                    }
                    else
                    {
                        ListBox lb2 = new ListBox();
                        lb2.FontSize = 10.5;

                        PolicyStatementAnalyser psa = new PolicyStatementAnalyser();
                        psa.ifThenUnlessTokenisation(p_stat.statement);

                        ListBoxItem lb2l1 = new ListBoxItem();
                        string if_content = "IF" + psa.if_content;
                        lb2l1.Content = if_content;
                        lb2.Items.Add(lb2l1);
                        ListBoxItem lb2l2 = new ListBoxItem();
                        string then_content = "   THEN" + psa.then_content;
                        lb2l2.Content = then_content;
                        lb2.Items.Add(lb2l2);
                        if (psa.unless_content != null)
                        {
                            ListBoxItem lb2l3 = new ListBoxItem();
                            string unless_content = "   UNLESS" + psa.unless_content;
                            lb2l3.Content = unless_content;
                            lb2.Items.Add(lb2l3);
                        }

                        if (transition_policies_lb.Items.Count % 2 == 0)
                        {
                            lb2.Background = Brushes.AliceBlue;
                            lb2.BorderBrush = Brushes.AliceBlue;
                        }
                        else
                        {
                            lb2.BorderBrush = Brushes.White;
                        }
                        cb.Content = lb2;
                    }
                    if (transition_policies_lb.Items.Count % 2 == 0)
                    {
                        l.Background = Brushes.AliceBlue;
                    }

                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(transition_policy_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(transition_policy_Checked));
                    ContentPresenter c2 = new ContentPresenter();
                    c2.Content = cb;                    
                    c1.Width = 15;
                    c2.Width = transition_policies_lb.Width - 60;
                    s.Children.Add(c1);
                    s.Children.Add(c2);
                    l.Content = s;

                    if (p_stat.statement.Equals("DO[NILL]"))
                    {
                        donillcb = cb;
                        cb.IsChecked = true;
                        donillcb.IsEnabled = false;
                        transition_policies_lb.Items.Insert(0, l);
                    }
                    else
                        transition_policies_lb.Items.Add(l);
                }
            }
        }

        private void reloadStateTransitionsPolicyStatementList(List<string> policyIDs)
        {
            int stat_no = 1;
            policy_statements = MisUseAnObjectsDB.loadAllPolicyStatementsFull(MainWindow.clusterName);

            if (policy_statements != null)
            {
                transition_policies_lb.Items.Clear();

                foreach (Policy p_stat in policy_statements)
                {
                    ListBoxItem l = new ListBoxItem();
                    StackPanel s = new StackPanel();
                    s.Orientation = System.Windows.Controls.Orientation.Horizontal;
                    ContentPresenter c1 = new ContentPresenter();
                    c1.Content = stat_no;
                    stat_no = stat_no + 1;

                    CheckBox cb = new CheckBox();
                    cb.Tag = p_stat.id;
                    
                    if (p_stat.statement.Equals("DO[NILL]"))
                    {
                        cb.Content = p_stat.statement;
                        l.Foreground = Brushes.DarkRed;
                        cb.Foreground = Brushes.DarkRed;
                    }
                    else
                    {
                        ListBox lb2 = new ListBox();
                        lb2.FontSize = 10.5;

                        PolicyStatementAnalyser psa = new PolicyStatementAnalyser();
                        psa.ifThenUnlessTokenisation(p_stat.statement);

                        ListBoxItem lb2l1 = new ListBoxItem();
                        string if_content = "IF" + psa.if_content;
                        lb2l1.Content = if_content;
                        lb2.Items.Add(lb2l1);
                        ListBoxItem lb2l2 = new ListBoxItem();
                        string then_content = "   THEN" + psa.then_content;
                        lb2l2.Content = then_content;
                        lb2.Items.Add(lb2l2);
                        if (psa.unless_content != null)
                        {
                            ListBoxItem lb2l3 = new ListBoxItem();
                            string unless_content = "   UNLESS" + psa.unless_content;
                            lb2l3.Content = unless_content;
                            lb2.Items.Add(lb2l3);
                        }

                        if (transition_policies_lb.Items.Count % 2 == 0)
                        {
                            lb2.Background = Brushes.AliceBlue;
                            lb2.BorderBrush = Brushes.AliceBlue;
                        }
                        else
                        {
                            lb2.BorderBrush = Brushes.White;
                        }
                        cb.Content = lb2;
                    }
                    if (transition_policies_lb.Items.Count % 2 == 0)
                    {
                        l.Background = Brushes.AliceBlue;
                    }
                    
                    foreach (string pid in policyIDs)
                    {
                        if (p_stat.id.Equals(pid))
                        {
                            cb.IsChecked = true;
                            break;
                        }
                    }
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(transition_policy_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(transition_policy_Checked));
                    //cb.IsEnabled = false;
                    ContentPresenter c2 = new ContentPresenter();
                    c2.Content = cb;
                    c1.Width = 15;
                    c2.Width = transition_policies_lb.Width - 60;
                    s.Children.Add(c1);
                    s.Children.Add(c2);
                    l.Content = s;

                    if (p_stat.statement.Equals("DO[NILL]"))
                    {
                        donillcb = cb;
                        donillcb.IsEnabled = false;
                        //cb.IsChecked = true;
                        transition_policies_lb.Items.Insert(0, l);
                    }
                    else
                        transition_policies_lb.Items.Add(l);
                }
            }
        }

        bool existingStateTransition(string transitionName, string startState, string endState, string assEventName, int policyID)
        {
            bool exist = false;

            if (allExistingStateTransitions == null)
            {
                allExistingStateTransitions = MisUseAnObjectsDB.loadAllStateTransitions(source_agent.assignedMachine.machineName, MainWindow.clusterName);
            }
            foreach (Transition eve in allExistingStateTransitions)
            {
                if (eve.machineName.Equals(source_agent.assignedMachine.machineName)
                        && eve.transitionName.Equals(transitionName)
                        && eve.startState.Equals(startState)
                        && eve.endState.Equals(endState)
                        && eve.associatedEevent.Equals(assEventName))
                {
                    foreach (string p in eve.policyIDs)
                    {
                        if (p.Equals(policyID))
                        {
                            exist = true;
                            break;
                        }
                    }
                }
            }
            return exist;
        }
        
        bool f_empty_p = false;
        bool f_cont_p = false;
        private void transition_policy_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox d_cb = (CheckBox)sender;
            string policyID = (string)d_cb.Tag;

            if (newStateTransition == null)
            {
                newStateTransition = new Transition();
                newStateTransition.machineName = source_agent.assignedMachine.machineName;
            }

            if (newStateTransition.policyIDs.Contains(policyID))
            {
                newStateTransition.removePolicyPD(policyID);
            }
            else
            {
                newStateTransition.addPolicyID(policyID);
            }


            if (newStateTransition.policyIDs.Count() == 0)
            {
                if (f_empty_p == false)
                {
                    f_empty_p = true;
                    donillcb.IsEnabled = false;
                    donillcb.IsChecked = true;

                }
            }

            if (!d_cb.Content.Equals("DO[NILL]"))
            {
                f_cont_p = false;
                f_empty_p = false;
                donillcb.IsChecked = false;
                donillcb.IsEnabled = false;
            }
            else if (d_cb.Content.Equals("DO[NILL]") && newStateTransition.policyIDs.Count() > 0)
            {
                if (f_cont_p == false)
                {
                    f_cont_p = true;
                    foreach (Policy p in policy_statements)
                    {
                        if (p.statement.Equals("DO[NILL]"))
                        {
                            if (newStateTransition.policyIDs.Count() > 1)
                            {
                                newStateTransition.policyIDs.Remove(p.id);
                                donillcb.IsEnabled = false;
                                donillcb.IsChecked = false;
                                break;
                            }
                        }
                    }
                }

            }

        }

        private void reloadEntsInComboBox()
        {
            allExistingStates = MisUseAnObjectsDB.loadAllStates(source_agent.assignedMachine.machineName, MainWindow.clusterName);
            allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(source_agent.assignedMachine.machineName, MainWindow.clusterName);

            start_state_cb.Items.Clear();
            end_state_cb.Items.Clear();
            associated_event_cb.Items.Clear();

            foreach (State state in allExistingStates)
            {
                start_state_cb.Items.Add(state.name);
                end_state_cb.Items.Add(state.name);
            }

            foreach (Event event_ in allExisitngEvents)
            {
                associated_event_cb.Items.Add(event_.name);
            }
        }

        private void loadStates()
        {
            allExistingStates = MisUseAnObjectsDB.loadAllStates(source_agent.assignedMachine.machineName, MainWindow.clusterName);

            states.Items.Clear();
            string startState = MisUseAnObjectsDB.getStartState(source_agent.assignedMachine.machineName, MainWindow.clusterName);
            string endState = MisUseAnObjectsDB.getEndState(source_agent.assignedMachine.machineName, MainWindow.clusterName);

            TreeViewItem item_n = new TreeViewItem();
            item_n.Header = "New..     ";
            item_n.Tag = "";
            item_n.FontStyle = FontStyles.Italic;
            item_n.Foreground = Brushes.Blue;
            item_n.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_TreeViewItem_Selected));
            states.Items.Add(item_n);

            foreach (State sta in allExistingStates)
            {
                if (!states.Items.Contains(sta.name))
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = sta.name;
                    item.Tag = sta.name;
                    item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_TreeViewItem_Selected));
                    if (sta.name.Equals(startState))
                    {
                        item.Foreground = Brushes.DarkSeaGreen;
                    }
                    else if (sta.name.Equals(endState))
                    {
                        item.Foreground = Brushes.DarkRed;
                    }

                    //if (sta.isMitigationPoint == true)
                    //{
                    //    item.Background = Brushes.LightYellow;
                    //}
                    if (sta.isMisusePoint == true)
                    {
                        item.Background = Brushes.OrangeRed;
                    }

                    MitigationReferences m_ref_s = MisUseAnObjectsDB.loadStateMitigationReferencesDB(sta.name, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                    if (m_ref_s.isEmpty == false)
                    {
                        item.Background = Brushes.Green;
                    }

                    TreeViewItem item_action = new TreeViewItem();
                    item_action.Header = "New.. (action)";
                    item_action.FontStyle = FontStyles.Italic;
                    item_action.Foreground = Brushes.Blue;
                    item_action.Tag = "new," + sta.name;
                    item_action.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));
                    item.Items.Add(item_action);
                    foreach (PMisuseAn.behaviour.model.Action action in sta.actions)
                    {
                        TreeViewItem item_act = new TreeViewItem();
                        item_act.Header = action.name;
                        item_act.Tag = action.name + "," + sta.name;
                        item_act.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));

                        //if (action.isMitigationPoint == true)
                        //{
                        //    item_act.Background = Brushes.LightYellow;
                        //}
                        if (action.isMisusePoint == true)
                        {
                            item_act.Background = Brushes.OrangeRed;
                        }
                        MitigationReferences m_ref = MisUseAnObjectsDB.loadStateActionMitigationReferencesDB(action.name, sta.name, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                        if (m_ref.isEmpty == false)
                        {
                            item_act.Background = Brushes.Green;
                        }

                        ContextMenu cm_act = new System.Windows.Controls.ContextMenu();
                        cm_act.Height = 60;
                        cm_act.Width = 150;
                        
                        MenuItem cm_mu_act = new MenuItem();
                        cm_mu_act.Header = "misuse point";
                        cm_mu_act.Tag = action.name + "," + sta.name;
                        if (action.isMisusePoint == true)
                        {
                            cm_mu_act.IsChecked = true;
                        }
                        cm_mu_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
                        cm_mu_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
                        cm_mu_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        cm_mu_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                        cm_mu_act.FontSize = 10;
                        //cm_mu_act.Background = Brushes.OrangeRed;
                        cm_mu_act.IsCheckable = true;

                        MenuItem cm_m_act = new MenuItem();
                        cm_m_act.Header = "Mitigation references";
                        cm_m_act.Tag = action.name + "," + sta.name;
                        if (action.isMisusePoint == false)
                        {
                            cm_m_act.IsEnabled = false;
                        }
                        if (m_ref.isEmpty == false)
                        {
                            cm_m_act.IsChecked = true;
                        }
                        cm_m_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
                        cm_m_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
                        cm_m_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        cm_m_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                        cm_m_act.FontSize = 10;
                        //cm_m_act.Background = Brushes.OrangeRed;
                        cm_m_act.IsCheckable = true;

                        //cm_act.Items.Add(cm_mp_act);
                        cm_act.Items.Add(cm_mu_act);
                        cm_act.Items.Add(cm_m_act);

                        item_act.ContextMenu = cm_act;
                        item.Items.Add(item_act);

                        item.IsExpanded = true;
                    }

                    ContextMenu cm = new System.Windows.Controls.ContextMenu();
                    cm.Height = 110;
                    cm.Width = 150;

                    MenuItem cm_i = new MenuItem();
                    cm_i.Header = "start state";
                    cm_i.Tag = sta.name;
                    cm_i.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(start_state_clicked));
                    cm_i.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_i.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_i.FontSize = 10;
                    cm_i.Foreground = Brushes.DarkSeaGreen;

                    BitmapImage cm_i_image = new BitmapImage();
                    cm_i_image.BeginInit();
                    Uri cm_i_Uri = new Uri("/PMisuseAn;component/images/startstate.gif", UriKind.RelativeOrAbsolute);
                    cm_i_image.UriSource = cm_i_Uri;
                    cm_i_image.EndInit();

                    Image cm_i_iconImage = new Image();
                    cm_i_iconImage.Source = cm_i_image;

                    cm_i.Icon = cm_i_iconImage;

                    MenuItem cm_i_e = new MenuItem();
                    cm_i_e.Header = "end state";
                    cm_i_e.Tag = sta.name;
                    cm_i_e.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(end_state_clicked));
                    cm_i_e.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_i_e.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_i_e.FontSize = 10;
                    cm_i_e.Foreground = Brushes.DarkRed;

                    BitmapImage cm_i_e_image = new BitmapImage();
                    cm_i_e_image.BeginInit();
                    Uri cm_i_e_Uri = new Uri("/PMisuseAn;component/images/stopstate.gif", UriKind.RelativeOrAbsolute);
                    cm_i_e_image.UriSource = cm_i_e_Uri;
                    cm_i_e_image.EndInit();

                    Image cm_i_e_iconImage = new Image();
                    cm_i_e_iconImage.Source = cm_i_e_image;

                    cm_i_e.Icon = cm_i_e_iconImage;
                    
                    MenuItem cm_mu = new MenuItem();
                    cm_mu.Header = "misuse point";
                    cm_mu.Tag = sta.name;
                    if (sta.isMisusePoint == true)
                    {
                        cm_mu.IsChecked = true;
                    }
                    cm_mu.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
                    cm_mu.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
                    cm_mu.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_mu.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_mu.FontSize = 10;
                    // cm_mu.Background = Brushes.OrangeRed;
                    cm_mu.IsCheckable = true;

                    MenuItem cm_m_mr = new MenuItem();
                    cm_m_mr.Header = "Mitigation references";
                    cm_m_mr.Tag = sta.name;

                    if (sta.isMisusePoint == false)
                    {
                        cm_m_mr.IsEnabled = false;
                    }
                    if (m_ref_s.isEmpty == false)
                    {
                        cm_m_mr.IsChecked = true;
                    }
                    cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
                    cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
                    cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_m_mr.FontSize = 10;
                    //cm_m_act.Background = Brushes.OrangeRed;
                    cm_m_mr.IsCheckable = true;

                    cm.Items.Add(cm_i);
                    cm.Items.Add(cm_i_e);
                    //cm.Items.Add(cm_mp);
                    cm.Items.Add(cm_mu);
                    cm.Items.Add(cm_m_mr);

                    item.ContextMenu = cm;

                    states.Items.Add(item);
                }
            }
        }

        private void loadStates(StateMachine machine)
        {
            states.Items.Clear();
            string startState = MisUseAnObjectsDB.getStartState(machine.machineName, MainWindow.clusterName);
            string endState = MisUseAnObjectsDB.getEndState(machine.machineName, MainWindow.clusterName);

            TreeViewItem item_n = new TreeViewItem();
            item_n.Header = "New..     ";
            item_n.Tag = "";
            item_n.FontStyle = FontStyles.Italic;
            item_n.Foreground = Brushes.Blue;
            item_n.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_TreeViewItem_Selected));
            states.Items.Add(item_n);

            foreach (State sta in machine.states)
            {
                if (!states.Items.Contains(sta.name))
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = sta.name;
                    item.Tag = sta.name;
                    item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_TreeViewItem_Selected));
                    if (sta.name.Equals(startState))
                    {
                        item.Foreground = Brushes.DarkSeaGreen;
                    }
                    else if (sta.name.Equals(endState))
                    {
                        item.Foreground = Brushes.DarkRed;
                    }

                    //if (sta.isMitigationPoint == true)
                    //{
                    //    item.Background = Brushes.LightYellow;
                    //}
                    if (sta.isMisusePoint == true)
                    {
                        item.Background = Brushes.OrangeRed;
                    }

                    MitigationReferences m_ref_s = MisUseAnObjectsDB.loadStateMitigationReferencesDB(sta.name, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                    if (m_ref_s.isEmpty == false)
                    {
                        item.Background = Brushes.Green;
                    }

                    TreeViewItem item_action = new TreeViewItem();
                    item_action.Header = "New.. (action)";
                    item_action.FontStyle = FontStyles.Italic;
                    item_action.Foreground = Brushes.Blue;
                    item_action.Tag = "new," + sta.name;
                    item_action.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));
                    item.Items.Add(item_action);
                    foreach (PMisuseAn.behaviour.model.Action action in sta.actions)
                    {
                        TreeViewItem item_act = new TreeViewItem();
                        item_act.Header = action.name;
                        item_act.Tag = action.name + "," + sta.name;
                        item_act.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));
                        //if (action.isMitigationPoint == true)
                        //{
                        //    item_act.Background = Brushes.LightYellow;
                        //}
                        if (action.isMisusePoint == true)
                        {
                            item_act.Background = Brushes.OrangeRed;
                        }

                        MitigationReferences m_ref = MisUseAnObjectsDB.loadStateActionMitigationReferencesDB(action.name, sta.name, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                        if (m_ref.isEmpty == false)
                        {
                            item_act.Background = Brushes.Green;
                        }

                        ContextMenu cm_act = new System.Windows.Controls.ContextMenu();
                        cm_act.Height = 60;
                        cm_act.Width = 150;

                        MenuItem cm_mu_act = new MenuItem();
                        cm_mu_act.Header = "misuse point";
                        cm_mu_act.Tag = action.name + "," + sta.name;
                        if (action.isMisusePoint == true)
                        {
                            cm_mu_act.IsChecked = true;
                        }
                        cm_mu_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
                        cm_mu_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
                        cm_mu_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        cm_mu_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                        cm_mu_act.FontSize = 10;
                        //cm_mu_act.Background = Brushes.OrangeRed;
                        cm_mu_act.IsCheckable = true;

                        MenuItem cm_m_act = new MenuItem();
                        cm_m_act.Header = "Mitigation references";
                        cm_m_act.Tag = action.name + "," + sta.name;

                        if (action.isMisusePoint == false)
                        {
                            cm_mu_act.IsEnabled = false;
                        }
                        if (m_ref.isEmpty == false)
                        {
                            cm_m_act.IsChecked = true;
                        }
                        cm_m_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
                        cm_m_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
                        cm_m_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        cm_m_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                        cm_m_act.FontSize = 10;
                        //cm_m_act.Background = Brushes.OrangeRed;
                        cm_m_act.IsCheckable = true;

                        //cm_act.Items.Add(cm_mp_act);
                        cm_act.Items.Add(cm_mu_act);
                        cm_act.Items.Add(cm_m_act);

                        item_act.ContextMenu = cm_act;
                        item.Items.Add(item_act);
                    }

                    ContextMenu cm = new System.Windows.Controls.ContextMenu();
                    cm.Height = 110;
                    cm.Width = 150;

                    MenuItem cm_i = new MenuItem();
                    cm_i.Header = "start state";
                    cm_i.Tag = sta.name;
                    cm_i.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(start_state_clicked));
                    cm_i.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_i.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_i.FontSize = 10;
                    cm_i.Foreground = Brushes.DarkSeaGreen;

                    BitmapImage cm_i_image = new BitmapImage();
                    cm_i_image.BeginInit();
                    Uri cm_i_Uri = new Uri("/PMisuseAn;component/images/startstate.gif", UriKind.RelativeOrAbsolute);
                    cm_i_image.UriSource = cm_i_Uri;
                    cm_i_image.EndInit();

                    Image cm_i_iconImage = new Image();
                    cm_i_iconImage.Source = cm_i_image;

                    cm_i.Icon = cm_i_iconImage;

                    MenuItem cm_i_e = new MenuItem();
                    cm_i_e.Header = "end state";
                    cm_i_e.Tag = sta.name;
                    cm_i_e.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(end_state_clicked));
                    cm_i_e.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_i_e.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_i_e.FontSize = 10;
                    cm_i_e.Foreground = Brushes.DarkRed;

                    BitmapImage cm_i_e_image = new BitmapImage();
                    cm_i_e_image.BeginInit();
                    Uri cm_i_e_Uri = new Uri("/PMisuseAn;component/images/stopstate.gif", UriKind.RelativeOrAbsolute);
                    cm_i_e_image.UriSource = cm_i_e_Uri;
                    cm_i_e_image.EndInit();

                    Image cm_i_e_iconImage = new Image();
                    cm_i_e_iconImage.Source = cm_i_e_image;

                    cm_i_e.Icon = cm_i_e_iconImage;
                    
                    MenuItem cm_mu = new MenuItem();
                    cm_mu.Header = "misuse point";
                    cm_mu.Tag = sta.name;
                    if (sta.isMisusePoint == true)
                    {
                        cm_mu.IsChecked = true;
                    }
                    cm_mu.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
                    cm_mu.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
                    cm_mu.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_mu.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_mu.FontSize = 10;
                    //cm_mu.Background = Brushes.OrangeRed;
                    cm_mu.IsCheckable = true;

                    MenuItem cm_m_mr = new MenuItem();
                    cm_m_mr.Header = "Mitigation references";
                    cm_m_mr.Tag = sta.name;

                    if (sta.isMisusePoint == false)
                    {
                        cm_m_mr.IsEnabled = false;
                    }
                    if (m_ref_s.isEmpty == false)
                    {
                        cm_m_mr.IsChecked = true;
                    }
                    cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
                    cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
                    cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_m_mr.FontSize = 10;
                    //cm_m_act.Background = Brushes.OrangeRed;
                    cm_m_mr.IsCheckable = true;

                    cm.Items.Add(cm_i);
                    cm.Items.Add(cm_i_e);
                    //cm.Items.Add(cm_mp);
                    cm.Items.Add(cm_mu);
                    cm.Items.Add(cm_m_mr);

                    item.ContextMenu = cm;

                    states.Items.Add(item);
                }
            }
        }
        
        private void mitigation_references_state_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string stateName = (string)cm_i.Tag;

            if (stateName != null)
            {
                MitigationReferences m_ref = MisUseAnObjectsDB.loadStateMitigationReferencesDB(stateName, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                MitigationReferenceWindow mrw = new MitigationReferenceWindow(m_ref, source_agent.assignedMachine.machineName, stateName);
                mrw.Owner = (Window)this.Parent;
                mrw.ShowDialog();

                MisUseAnObjectsDB.addStateMitigationReferencesDB(stateName, m_ref, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                loadStates();
                loadTransitions();
                genStateMachineGraph(source_agent.agentName);
            }
        }

        private void misuse_point_state_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string stateName = (string)cm_i.Tag;

            if (stateName != null)
            {
                if (cm_i.IsChecked == true)
                {
                    MisUseAnObjectsDB.addStateMisusePointDB(stateName, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                }
                else if (cm_i.IsChecked == false)
                {
                    MisUseAnObjectsDB.removeStateMisusePointDB(stateName, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                }
                loadStates();
                genStateMachineGraph(source_agent.agentName);
            }
        }

        private void start_state_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string stateName = (string)cm_i.Tag;
            if (stateName != null)
            {
                MisUseAnObjectsDB.addStateMachineStartStateDB(stateName, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                loadStates();
                genStateMachineGraph(source_agent.agentName);
            }
        }

        private void end_state_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string stateName = (string)cm_i.Tag;
            if (stateName != null)
            {
                MisUseAnObjectsDB.addStateMachineEndStateDB(stateName, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                loadStates();
                genStateMachineGraph(source_agent.agentName);
            }
        }

        private void mitigation_references_state_action_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string tag_id = (string)cm_i.Tag;
            string[] tag_split = tag_id.Split(',');

            string actionName = tag_split[0];
            string stateName = tag_split[1];

            if (stateName != null && actionName != null)
            {
                MitigationReferences m_ref = MisUseAnObjectsDB.loadStateActionMitigationReferencesDB(actionName, stateName, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                string t_label = stateName + "(" + actionName + ")";
                MitigationReferenceWindow mrw = new MitigationReferenceWindow(m_ref, source_agent.assignedMachine.machineName, t_label);
                mrw.Owner = (Window)this.Parent;
                mrw.ShowDialog();

                MisUseAnObjectsDB.addStateActionMitigationReferencesDB(actionName, stateName, m_ref, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                loadStates();
                loadTransitions();
                genStateMachineGraph(source_agent.agentName);
            }
        }

        private void misuse_point_state_action_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string tag_id = (string)cm_i.Tag;
            string[] tag_split = tag_id.Split(',');

            string actionName = tag_split[0];
            string stateName = tag_split[1];

            if (stateName != null && actionName != null)
            {
                if (cm_i.IsChecked == true)
                {
                    //MisUseAnObjectsDB.addStateActionMisusePointDB(actionName, stateName, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                }
                else if (cm_i.IsChecked == false)
                {
                    //MisUseAnObjectsDB.removeStateActionMisusePointDB(actionName, stateName, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                }
                loadStates();
                genStateMachineGraph(source_agent.agentName);
            }
        }

        private void state_action_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isStateActionSelection = true;
            TreeViewItem d_cb = (TreeViewItem)sender;

            string tag_id = (string)d_cb.Tag;
            string[] tag_split = tag_id.Split(',');

            string actionName = tag_split[0];
            string stateName = tag_split[1];
            stateName_ = stateName;

            if (actionName.Equals("new"))
            {
                isStateActionUpdate = false;
                //allExistingStateActions = MisUseAnObjectsDB.loadAllStateActions(machineName_, stateName);
                newAction = new PMisuseAn.behaviour.model.Action();
                loadAttributesToStateActionOperationalAttributes();
                newAction.machineName = source_agent.assignedMachine.machineName;
                newAction.stateName = stateName;
                newAction.clusterName = MainWindow.clusterName;
                new_ent_name_tb.Text = "";
                new_ent_name_tb.IsReadOnly = false;
                new_ent_desc_tb.Text = "";

                state_action_apply_b.Visibility = System.Windows.Visibility.Visible;
                state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                isStateActionUpdate = true;
                newAction = MisUseAnObjectsDB.loadStateActionDB(actionName, stateName, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                if (newAction != null)
                {
                    reloadAttributesToStateActionOperationalAttributes(newAction.operationalAttributes_);
                    new_ent_name_tb.Text = newAction.name;
                    new_ent_name_tb.IsReadOnly = true;
                    new_ent_desc_tb.Text = newAction.description;

                    state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_update_b.Visibility = System.Windows.Visibility.Visible;
                    state_action_delete_b.Visibility = System.Windows.Visibility.Visible;
                }

            }
            new_ent_name_tb.Visibility = System.Windows.Visibility.Visible;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Visible;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Visible;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Visible;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Visible;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
        }

        private void state_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            TreeViewItem d_cb = (TreeViewItem)sender;
            stateActionSelected_tv = d_cb;

            isStateSelection = true;

            if (isStateActionSelection == false)
            {
                string tag_id = (string)d_cb.Tag;
                if (tag_id.Equals(""))
                {
                    isStateUpdate = false;
                    allExistingStates = MisUseAnObjectsDB.loadAllStates(source_agent.assignedMachine.machineName, MainWindow.clusterName);
                    newState = new State();
                    newState.machineName = source_agent.assignedMachine.machineName;
                    newState.clusterName = MainWindow.clusterName;
                    new_ent_name_tb.Text = "";
                    new_ent_name_tb.IsReadOnly = false;
                    new_ent_desc_tb.Text = "";

                    define_state_b.Visibility = System.Windows.Visibility.Visible;
                    delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                    update_state_b.Visibility = System.Windows.Visibility.Hidden;
                }
                else
                {
                    newState = MisUseAnObjectsDB.loadStateDB(tag_id, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                    if (newState != null)
                    {
                        isStateUpdate = true;
                        new_ent_name_tb.Text = newState.name;
                        new_ent_name_tb.IsReadOnly = true;
                        new_ent_desc_tb.Text = newState.description;
                       
                        if (newState.isCallable)
                        {
                            isCallableState_cb.IsChecked = true;
                        }
                        else
                        {
                            isCallableState_cb.IsChecked = false;
                        }

                        define_state_b.Visibility = System.Windows.Visibility.Hidden;
                        delete_state_b.Visibility = System.Windows.Visibility.Visible;
                        update_state_b.Visibility = System.Windows.Visibility.Visible;
                    }
                }
                new_ent_name_tb.Visibility = System.Windows.Visibility.Visible;
                new_ent_Name_l.Visibility = System.Windows.Visibility.Visible;
                apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                new_ent_desc_tb.Visibility = System.Windows.Visibility.Visible;
                new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                desc_l.Visibility = System.Windows.Visibility.Visible;
                update_event_b.Visibility = System.Windows.Visibility.Hidden;
                delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                start_state_l.Visibility = System.Windows.Visibility.Hidden;
                start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                end_state_l.Visibility = System.Windows.Visibility.Hidden;
                end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                isCallableState_cb.Visibility = System.Windows.Visibility.Visible;
                isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                isStateActionSelection = false;
            }
        }
        
        public void reloadAttributesToStateActionOperationalAttributes(List<string> operationalAttributes)
        {

            agentAttributes = MisUseAnObjectsDB.loadAgentAttributes(MainWindow.clusterName);
            //functionalAttributes = MisUseAnObjectsDB.loadFunctionalAttributes(MainWindow.clusterName);
            environmentalAttributes = MisUseAnObjectsDB.loadEnvironmentAttributes(MainWindow.clusterName);

            agentAttributes_lb.Items.Clear();
            //functionalAttributes_lb.Items.Clear();
            environmentAttributes_lb.Items.Clear();

            foreach (Attribute att in agentAttributes)
            {
                bool contained = agentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    foreach (string opatt in operationalAttributes)
                    {
                        if (att.name.Equals(opatt))
                        {
                            cb.IsChecked = true;
                            break;
                        }
                    }
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    agentAttributes_lb.Items.Add(cb);
                }
            }

            //foreach (Attribute att in functionalAttributes)
            //{
            //    bool contained = functionalAttributes_lb.Items.Contains(att.name);
            //    if (contained == false)
            //    {
            //        CheckBox cb = new CheckBox();
            //        cb.Tag = att.name;
            //        cb.Content = att.name;
            //        foreach (string opatt in operationalAttributes)
            //        {
            //            if (att.name.Equals(opatt))
            //            {
            //                cb.IsChecked = true;
            //                break;
            //            }
            //        }
            //        cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
            //        cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
            //        functionalAttributes_lb.Items.Add(cb);
            //    }
            //}

            foreach (Attribute att in environmentalAttributes)
            {
                bool contained = environmentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    foreach (string opatt in operationalAttributes)
                    {
                        if (att.name.Equals(opatt))
                        {
                            cb.IsChecked = true;
                            break;
                        }
                    }
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    environmentAttributes_lb.Items.Add(cb);
                }
            }
        }

        public void loadAttributesToStateActionOperationalAttributes()
        {
            List<string> agentAttributes_s = new List<string>();
            List<string> functionalAttributes_s = new List<string>();
            List<string> environmentalAttributes_s = new List<string>();

            agentAttributes = MisUseAnObjectsDB.loadAgentAttributes(MainWindow.clusterName);
            //functionalAttributes = MisUseAnObjectsDB.loadFunctionalAttributes(MainWindow.clusterName);
            environmentalAttributes = MisUseAnObjectsDB.loadEnvironmentAttributes(MainWindow.clusterName);

            agentAttributes_lb.Items.Clear();
            //functionalAttributes_lb.Items.Clear();
            environmentAttributes_lb.Items.Clear();

            foreach (Attribute att in agentAttributes)
            {
                agentAttributes_s.Add(att.name);

                bool contained = agentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    agentAttributes_lb.Items.Add(cb);
                }
            }

            //foreach (Attribute att in functionalAttributes)
            //{
            //    functionalAttributes_s.Add(att.name);
            //    bool contained = functionalAttributes_lb.Items.Contains(att.name);
            //    if (contained == false)
            //    {
            //        CheckBox cb = new CheckBox();
            //        cb.Tag = att.name;
            //        cb.Content = att.name;
            //        cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
            //        cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
            //        functionalAttributes_lb.Items.Add(cb);
            //    }
            //}

            foreach (Attribute att in environmentalAttributes)
            {
                environmentalAttributes_s.Add(att.name);
                bool contained = environmentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    environmentAttributes_lb.Items.Add(cb);
                }
            }
        }

        private void state_action_op_att_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox d_cb = (CheckBox)sender;
            string tag_id = (string)d_cb.Tag;

            string actionName = new_ent_name_tb.Text;
            actionName = actionName.Trim();
            actionName = actionName.TrimEnd('\n');
            actionName = actionName.TrimEnd('\r');

            if (actionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL action name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);

                d_cb.IsChecked = false;

                return;
            }
            if (isStateActionUpdate == false)
            {
                if (existingStateAction(actionName, stateName_) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, actionName + " action already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    d_cb.IsChecked = false;

                    return;
                }
            }

            if (newAction == null)
            {
                newAction = new PMisuseAn.behaviour.model.Action();
                newAction.machineName = source_agent.assignedMachine.machineName;
                newAction.stateName = stateName_;
                newAction.clusterName = MainWindow.clusterName;
            }
            newAction.name = actionName;

            if (newAction.operationalAttributes_.Contains(tag_id))
            {
                newAction.removeOperationalAttribute(tag_id);
                MisUseAnObjectsDB.deleteStateActionOperationalAttributeDB(source_agent.assignedMachine.machineName, stateName_, actionName, tag_id, MainWindow.clusterName);
            }
            else
            {
                newAction.addOperationalAttribute(tag_id);
                MisUseAnObjectsDB.addStateActionOperationalAttributeDB(newAction, tag_id, MainWindow.clusterName);
            }
        }
        
        bool existingStateAction(string stateName, string actionName)
        {
            bool exist = false;

            if (allExistingStateActions == null)
            {
                allExistingStateActions = MisUseAnObjectsDB.loadAllStateActions(source_agent.assignedMachine.machineName, stateName, MainWindow.clusterName);

            }
            foreach (PMisuseAn.behaviour.model.Action action in allExistingStateActions)
            {
                if (action.name.Equals(actionName))
                {
                    exist = true;
                    break;
                }
            }
            return exist;
        }

        private void events_root_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isEventRootSelection = true;
        }
        private void states_root_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isStateRootSelection = true;
        }
        private void transitions_root_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isTransitionRootSelection = true;
        }

        private void state_machine_root_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            TreeViewItem d_cb = (TreeViewItem)sender;
            string tag_id = (string)d_cb.Tag;

            if (isStateActionSelection == false && isStateSelection == false
                && isTransitionSelection == false && isEventSelection == false
                && isEventRootSelection == false && isStateRootSelection == false
                && isTransitionRootSelection == false)
            {
                if (tag_id.Equals("root"))
                {
                    new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                    desc_l.Visibility = System.Windows.Visibility.Hidden;
                    update_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                    define_state_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                    update_state_b.Visibility = System.Windows.Visibility.Hidden;
                    operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                    state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                    transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                    update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    start_state_l.Visibility = System.Windows.Visibility.Hidden;
                    start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                    associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                    end_state_l.Visibility = System.Windows.Visibility.Hidden;
                    end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
                    isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
                }
            }

            else
            {
                isStateActionSelection = false;
                isStateSelection = false;
                isEventSelection = false;
                isTransitionSelection = false;
                isTransitionRootSelection = false;
                isStateRootSelection = false;
                isEventRootSelection = false;
            } 
        }
        
        private void loadEvents(StateMachine machine)
        {
            events.Items.Clear();

            TreeViewItem item_n = new TreeViewItem();
            item_n.Header = "New..     ";
            item_n.Tag = "";
            item_n.FontStyle = FontStyles.Italic;
            item_n.Foreground = Brushes.Blue;
            item_n.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(event_TreeViewItem_Selected));
            events.Items.Add(item_n);

            foreach (Event eve in machine.events)
            {
                if (!events.Items.Contains(eve.name))
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = eve.name;
                    item.Tag = eve.name;
                    item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(event_TreeViewItem_Selected));
                    
                    events.Items.Add(item);
                }
            }
        }
        
        private void event_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isEventSelection = true;

            TreeViewItem d_cb = (TreeViewItem)sender;
            string tag_id = (string)d_cb.Tag;
            if (tag_id.Equals(""))
            {
                isEventUpdate = false;
                allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(source_agent.assignedMachine.machineName, MainWindow.clusterName);
                newEvent = new Event();
                newEvent.machineName = source_agent.assignedMachine.machineName;
                newEvent.clusterName = MainWindow.clusterName;
                new_ent_name_tb.Text = "";
                new_ent_name_tb.IsReadOnly = false;
                new_ent_desc_tb.Text = "";
                loadAttributesToEventOperationalAttributes();

                loadingTriggers = true;
                time_event_cb.IsChecked = false;
                call_event_cb.IsChecked = false;
                signal_event_cb.IsChecked = false;
                change_event_cb.IsChecked = false;
                loadingTriggers = false;

                apply_new_event_b.Visibility = System.Windows.Visibility.Visible;
                update_event_b.Visibility = System.Windows.Visibility.Hidden;
                delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                newEvent = MisUseAnObjectsDB.loadEventDB(tag_id, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                if (newEvent != null)
                {
                    isEventUpdate = true;
                    new_ent_name_tb.Text = newEvent.name;
                    new_ent_name_tb.IsReadOnly = true;
                    new_ent_desc_tb.Text = newEvent.description;
                    reloadAttributesToEventOperationalAttributes(newEvent.operationalAttributes_);

                    if (newEvent.type.Equals("request"))
                    {
                        request_event_rb.IsChecked = true;
                    }
                    else
                    {
                        response_event_rb.IsChecked = true;
                    }

                    loadingTriggers = true;
                    time_event_cb.IsChecked = false;
                    call_event_cb.IsChecked = false;
                    signal_event_cb.IsChecked = false;
                    change_event_cb.IsChecked = false;
                    foreach (string trigger in newEvent.triggers)
                    {
                        if (trigger.Equals("timed"))
                        {
                            time_event_cb.IsChecked = true;
                        }
                        else if (trigger.Equals("call"))
                        {
                            call_event_cb.IsChecked = true;
                        }
                        else if (trigger.Equals("signal"))
                        {
                            signal_event_cb.IsChecked = true;
                        }
                        else if (trigger.Equals("change"))
                        {
                            change_event_cb.IsChecked = true;
                        }
                    }
                    loadingTriggers = false;

                    apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                    update_event_b.Visibility = System.Windows.Visibility.Visible;
                    delete_event_b.Visibility = System.Windows.Visibility.Visible;
                }
            }
            new_ent_name_tb.Visibility = System.Windows.Visibility.Visible;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Visible;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Visible;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Visible;
            desc_l.Visibility = System.Windows.Visibility.Visible;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Visible;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

        }

        public void reloadAttributesToEventOperationalAttributes(List<string> operationalAttributes)
        {

            agentAttributes = MisUseAnObjectsDB.loadAgentAttributes(MainWindow.clusterName);
            //functionalAttributes = MisUseAnObjectsDB.loadFunctionalAttributes(MainWindow.clusterName);
            environmentalAttributes = MisUseAnObjectsDB.loadEnvironmentAttributes(MainWindow.clusterName);

            agentAttributes_lb.Items.Clear();
            //functionalAttributes_lb.Items.Clear();
            environmentAttributes_lb.Items.Clear();

            foreach (Attribute att in agentAttributes)
            {
                bool contained = agentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    foreach (string opatt in operationalAttributes)
                    {
                        if (att.name.Equals(opatt))
                        {
                            cb.IsChecked = true;
                            break;
                        }
                    }
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    agentAttributes_lb.Items.Add(cb);
                }
            }

            //foreach (Attribute att in functionalAttributes)
            //{
            //    bool contained = functionalAttributes_lb.Items.Contains(att.name);
            //    if (contained == false)
            //    {
            //        CheckBox cb = new CheckBox();
            //        cb.Tag = att.name;
            //        cb.Content = att.name;
            //        foreach (string opatt in operationalAttributes)
            //        {
            //            if (att.name.Equals(opatt))
            //            {
            //                cb.IsChecked = true;
            //                break;
            //            }
            //        }
            //        cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
            //        cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
            //        functionalAttributes_lb.Items.Add(cb);
            //    }
            //}

            foreach (Attribute att in environmentalAttributes)
            {
                bool contained = environmentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    foreach (string opatt in operationalAttributes)
                    {
                        if (att.name.Equals(opatt))
                        {
                            cb.IsChecked = true;
                            break;
                        }
                    }
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    environmentAttributes_lb.Items.Add(cb);
                }
            }
        }

        public void loadAttributesToEventOperationalAttributes()
        {
            List<string> agentAttributes_s = new List<string>();
            List<string> functionalAttributes_s = new List<string>();
            List<string> environmentalAttributes_s = new List<string>();

            agentAttributes = MisUseAnObjectsDB.loadAgentAttributes(MainWindow.clusterName);
            //functionalAttributes = MisUseAnObjectsDB.loadFunctionalAttributes(MainWindow.clusterName);
            environmentalAttributes = MisUseAnObjectsDB.loadEnvironmentAttributes(MainWindow.clusterName);

            agentAttributes_lb.Items.Clear();
            //functionalAttributes_lb.Items.Clear();
            environmentAttributes_lb.Items.Clear();

            foreach (Attribute att in agentAttributes)
            {
                agentAttributes_s.Add(att.name);

                bool contained = agentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    agentAttributes_lb.Items.Add(cb);
                }
            }

            //foreach (Attribute att in functionalAttributes)
            //{
            //    functionalAttributes_s.Add(att.name);
            //    bool contained = functionalAttributes_lb.Items.Contains(att.name);
            //    if (contained == false)
            //    {
            //        CheckBox cb = new CheckBox();
            //        cb.Tag = att.name;
            //        cb.Content = att.name;
            //        cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
            //        cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
            //        functionalAttributes_lb.Items.Add(cb);
            //    }
            //}

            foreach (Attribute att in environmentalAttributes)
            {
                environmentalAttributes_s.Add(att.name);
                bool contained = environmentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    environmentAttributes_lb.Items.Add(cb);
                }
            }
        }

        private void event_op_att_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox d_cb = (CheckBox)sender;
            string tag_id = (string)d_cb.Tag;

            string eventName = new_ent_name_tb.Text;
            eventName = eventName.Trim();
            eventName = eventName.TrimEnd('\n');
            eventName = eventName.TrimEnd('\r');

            if (eventName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL event name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);

                d_cb.IsChecked = false;

                return;
            }
            if (isEventUpdate == false)
            {
                if (existingEvent(eventName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, eventName + " event already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    d_cb.IsChecked = false;

                    return;
                }
            }

            if (newEvent == null)
            {
                newEvent = new Event();
                newEvent.machineName = source_agent.assignedMachine.machineName;
                newEvent.clusterName = MainWindow.clusterName;
            }
            string eventDesc = new_ent_desc_tb.Text;
            newEvent.name = eventName;
            newEvent.description = eventDesc;

            string eventType = "";
            if (request_event_rb.IsChecked == true)
            {
                eventType = "request";
            }
            else
            {
                eventType = "response";
            }
            newEvent.type = eventType;

            if (newEvent.operationalAttributes_.Contains(tag_id))
            {
                newEvent.removeOperationalAttribute(tag_id);
                MisUseAnObjectsDB.deleteEventOperationalAttributeDB(tag_id, eventName, source_agent.assignedMachine.machineName, MainWindow.clusterName);
            }
            else
            {
                newEvent.addOperationalAttribute(tag_id);
                MisUseAnObjectsDB.addEventOperationalAttributeDB(newEvent, tag_id, MainWindow.clusterName);
            }
        }

        bool existingEvent(string eventName)
        {
            bool exist = false;

            if (allExisitngEvents == null)
            {
                allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(source_agent.assignedMachine.machineName, MainWindow.clusterName);
            }
            foreach (Event eve in allExisitngEvents)
            {
                if (eve.name.Equals(eventName))
                {
                    exist = true;
                    break;
                }
            }
            return exist;
        }
        
        private void new_event_trigger_CheckedUnchecked(object sender, RoutedEventArgs e)
        {
            if (loadingTriggers == false)
            {
                CheckBox d_cb = (CheckBox)sender;
                string eventName = new_ent_name_tb.Text;
                eventName = eventName.Trim();
                eventName = eventName.TrimEnd('\n');
                eventName = eventName.TrimEnd('\r');

                if (eventName.Count() == 0)
                {
                    MessageBoxResult result = MessageBox.Show(this, "NULL event name...",
                                "error", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    d_cb.IsChecked = false;

                    return;
                }
                if (isEventUpdate == false)
                {
                    if (existingEvent(eventName) == true)
                    {
                        MessageBoxResult result = MessageBox.Show(this, eventName + " event already exist...",
                                    "Conflict", MessageBoxButton.OK,
                                    MessageBoxImage.Information);

                        d_cb.IsChecked = false;

                        return;
                    }
                }

                if (newEvent == null)
                {
                    newEvent = new Event();
                    newEvent.machineName = source_agent.assignedMachine.machineName;
                    newEvent.clusterName = MainWindow.clusterName;
                }
                newEvent.name = eventName;

                string eventType = "";
                if (request_event_rb.IsChecked == true)
                {
                    eventType = "request";
                }
                else
                {
                    eventType = "response";
                }
                newEvent.type = eventType;

                string trigger = (string)d_cb.Tag;

                if (newEvent.triggers.Contains(trigger))
                {
                    newEvent.removeTrigger(trigger);
                    MisUseAnObjectsDB.deleteEventTriggerDB(newEvent.name, trigger, source_agent.assignedMachine.machineName, MainWindow.clusterName);
                }
                else
                {
                    newEvent.addTrigger(trigger);
                    MisUseAnObjectsDB.addEventDB(newEvent, MainWindow.clusterName);
                }
            }
        }

        private void update_event_b_Click(object sender, RoutedEventArgs e)
        {
            string eventName = new_ent_name_tb.Text;
            eventName = eventName.Trim();
            eventName = eventName.TrimEnd('\n');
            eventName = eventName.TrimEnd('\r');

            if (eventName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL event name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            if (isEventUpdate == false)
            {
                if (existingEvent(eventName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, eventName + " event already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }

            }

            if (newEvent == null)
            {
                newEvent = new Event();
                newEvent.clusterName = MainWindow.clusterName;
                return;
            }

            string eventDesc = new_ent_desc_tb.Text;
            newEvent.name = eventName;
            newEvent.description = eventDesc;

            string eventType = "";
            if (request_event_rb.IsChecked == true)
            {
                eventType = "request";
            }
            else
            {
                eventType = "response";
            }
            newEvent.type = eventType;

            MisUseAnObjectsDB.updateEventDB(newEvent, MainWindow.clusterName);

            allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(source_agent.assignedMachine.machineName, MainWindow.clusterName);
            newEvent = new Event();
            newEvent.machineName = source_agent.assignedMachine.machineName;
            newEvent.clusterName = MainWindow.clusterName;
            //reloadAttInNew_eventList();
            //loadAttributesToNewEventCategoryList();
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";

            loadingTriggers = true;
            time_event_cb.IsChecked = false;
            call_event_cb.IsChecked = false;
            signal_event_cb.IsChecked = false;
            change_event_cb.IsChecked = false;
            loadingTriggers = false;

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

            genStateMachineGraph(source_agent.agentName);
        }

        private void delete_event_b_Click(object sender, RoutedEventArgs e)
        {
            string eventName = new_ent_name_tb.Text;
            eventName = eventName.Trim();
            eventName = eventName.TrimEnd('\n');
            eventName = eventName.TrimEnd('\r');

            if (eventName.Count() > 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "confirm delete of " + eventName + " event",
                            "Confirm", MessageBoxButton.YesNo,
                            MessageBoxImage.Information);

                if (result == MessageBoxResult.No)
                {
                    return;
                }
                else
                {
                    MisUseAnObjectsDB.deleteEventDB(source_agent.assignedMachine.machineName, eventName, MainWindow.clusterName);
                    if (source_agent.assignedMachine != null)
                    {
                        source_agent.assignedMachine.removeEvent(eventName);
                    }

                    allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(source_agent.assignedMachine.machineName, MainWindow.clusterName);
                    newEvent = new Event();
                    newEvent.machineName = source_agent.assignedMachine.machineName;
                    newEvent.clusterName = MainWindow.clusterName;
                    //reloadAttInNew_eventList();
                    //loadAttributesToNewEventCategoryList();
                    new_ent_name_tb.Text = "";
                    new_ent_desc_tb.Text = "";

                    loadingTriggers = true;
                    time_event_cb.IsChecked = false;
                    call_event_cb.IsChecked = false;
                    signal_event_cb.IsChecked = false;
                    change_event_cb.IsChecked = false;
                    loadingTriggers = false;

                    new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                    desc_l.Visibility = System.Windows.Visibility.Hidden;
                    update_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                    update_state_b.Visibility = System.Windows.Visibility.Hidden;
                    define_state_b.Visibility = System.Windows.Visibility.Hidden;
                    operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                    state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                    transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                    update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    start_state_l.Visibility = System.Windows.Visibility.Hidden;
                    start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                    associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                    end_state_l.Visibility = System.Windows.Visibility.Hidden;
                    end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
                    isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

                    foreach (TreeViewItem item in events.Items)
                    {
                        if (item.Tag.Equals(eventName))
                        {
                            events.Items.Remove(item);
                            break;
                        }
                    }
                    loadTransitions();
                }
            }
            genStateMachineGraph(source_agent.agentName);
        }
        
        private void apply_new_event_b_Click(object sender, RoutedEventArgs e)
        {
            string eventName = new_ent_name_tb.Text;
            eventName = eventName.Trim();
            eventName = eventName.TrimEnd('\n');
            eventName = eventName.TrimEnd('\r');

            if (eventName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL event name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            if (isEventUpdate == false)
            {
                if (existingEvent(eventName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, eventName + " event already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }
            }

            if (newEvent == null)
            {
                newEvent = new Event();
                newEvent.machineName = source_agent.assignedMachine.machineName;
                newEvent.clusterName = MainWindow.clusterName;
            }

            string eventDesc = new_ent_desc_tb.Text;
            newEvent.name = eventName;
            newEvent.description = eventDesc;

            string eventType = "";
            if (request_event_rb.IsChecked == true)
            {
                eventType = "request";
            }
            else
            {
                eventType = "response";
            }
            newEvent.type = eventType;

            MisUseAnObjectsDB.addEventDB(newEvent, MainWindow.clusterName);

            TreeViewItem tvi = new TreeViewItem();
            tvi.Tag = newEvent.name;
            tvi.Header = newEvent.name;
            tvi.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(event_TreeViewItem_Selected));
            
            events.Items.Add(tvi);

            allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(source_agent.assignedMachine.machineName, MainWindow.clusterName);
            newEvent = new Event();
            newEvent.machineName = source_agent.assignedMachine.machineName;
            newEvent.clusterName = MainWindow.clusterName;
            //loadAttributesToNewEventCategoryList();
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";

            loadingTriggers = true;
            time_event_cb.IsChecked = false;
            call_event_cb.IsChecked = false;
            signal_event_cb.IsChecked = false;
            change_event_cb.IsChecked = false;
            loadingTriggers = false;

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

            //genStateMachineGraph();
        }

        private void define_state_b_Click(object sender, RoutedEventArgs e)
        {
            string stateName = new_ent_name_tb.Text;
            stateName = stateName.Trim();
            stateName = stateName.TrimEnd('\n');
            stateName = stateName.TrimEnd('\r');

            if (stateName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL state name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            if (isStateUpdate == false)
            {
                if (existingState(stateName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, stateName + " state already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }
            }


            if (newState == null)
            {
                newState = new State();
                newState.clusterName = MainWindow.clusterName;
            }

            newState.name = stateName;
            newState.machineName = source_agent.assignedMachine.machineName;
            string stateDesc = new_ent_desc_tb.Text;
            newState.description = stateDesc;

            if (isCallableState_cb.IsChecked == true)
            {
                newState.isCallable = true;
            }
            else
            {
                newState.isCallable = false;
            }

            MisUseAnObjectsDB.addStateDB(newState, MainWindow.clusterName);

            TreeViewItem tvi = new TreeViewItem();
            tvi.Tag = newState.name;
            tvi.Header = newState.name;
            tvi.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_TreeViewItem_Selected));

            if (newState.name.Equals(sourceMachineStartState))
            {
                tvi.Foreground = Brushes.DarkSeaGreen;
            }
            else if (newState.name.Equals(sourceMachineEndState))
            {
                tvi.Foreground = Brushes.DarkRed;
            }

            //if (newState.isMitigationPoint == true)
            //{
            //    tvi.Background = Brushes.LightYellow;
            //}
            if (newState.isMisusePoint == true)
            {
                tvi.Background = Brushes.OrangeRed;
            }

            MitigationReferences m_ref_s = MisUseAnObjectsDB.loadStateMitigationReferencesDB(newState.name, source_agent.assignedMachine.machineName, MainWindow.clusterName);

            if (m_ref_s.isEmpty == false)
            {
                tvi.Background = Brushes.Green;
            }

            TreeViewItem item_action = new TreeViewItem();
            item_action.Header = "New.. (action)";
            item_action.FontStyle = FontStyles.Italic;
            item_action.Foreground = Brushes.Blue;
            item_action.Tag = "new," + newState.name;
            item_action.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));
            tvi.Items.Add(item_action);
            tvi.IsExpanded = true;

            ContextMenu cm = new System.Windows.Controls.ContextMenu();
            cm.Height = 110;
            cm.Width = 150;

            MenuItem cm_i = new MenuItem();
            cm_i.Header = "start state";
            cm_i.Tag = newState.name;
            cm_i.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(start_state_clicked));
            cm_i.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_i.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_i.FontSize = 10;
            cm_i.Foreground = Brushes.DarkSeaGreen;

            BitmapImage cm_i_image = new BitmapImage();
            cm_i_image.BeginInit();
            Uri cm_i_Uri = new Uri("/PMisuseAn;component/images/startstate.gif", UriKind.RelativeOrAbsolute);
            cm_i_image.UriSource = cm_i_Uri;
            cm_i_image.EndInit();

            Image cm_i_iconImage = new Image();
            cm_i_iconImage.Source = cm_i_image;

            cm_i.Icon = cm_i_iconImage;

            MenuItem cm_i_e = new MenuItem();
            cm_i_e.Header = "end state";
            cm_i_e.Tag = newState.name;
            cm_i_e.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(end_state_clicked));
            cm_i_e.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_i_e.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_i_e.FontSize = 10;
            cm_i_e.Foreground = Brushes.DarkRed;

            BitmapImage cm_i_e_image = new BitmapImage();
            cm_i_e_image.BeginInit();
            Uri cm_i_e_Uri = new Uri("/PMisuseAn;component/images/stopstate.gif", UriKind.RelativeOrAbsolute);
            cm_i_e_image.UriSource = cm_i_e_Uri;
            cm_i_e_image.EndInit();

            Image cm_i_e_iconImage = new Image();
            cm_i_e_iconImage.Source = cm_i_e_image;

            cm_i_e.Icon = cm_i_e_iconImage;

            //MenuItem cm_mp = new MenuItem();
            //cm_mp.Header = "mitigation point";
            //cm_mp.Tag = newState.name;
            //if (newState.isMitigationPoint == true)
            //{
            //    cm_mp.IsChecked = true;
            //}
            //cm_mp.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_state_clicked));
            //cm_mp.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_state_clicked));
            //cm_mp.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            //cm_mp.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            //cm_mp.FontSize = 10;
            //cm_mp.Background = Brushes.LightYellow;
            //cm_mp.IsCheckable = true;

            MenuItem cm_mu = new MenuItem();
            cm_mu.Header = "misuse point";
            cm_mu.Tag = newState.name;
            if (newState.isMisusePoint == true)
            {
                cm_mu.IsChecked = true;
            }
            cm_mu.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
            cm_mu.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
            cm_mu.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_mu.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_mu.FontSize = 10;
            // cm_mu.Background = Brushes.OrangeRed;
            cm_mu.IsCheckable = true;

            MenuItem cm_m_mr = new MenuItem();
            cm_m_mr.Header = "Mitigation references";
            cm_m_mr.Tag = newState.name;
            if (newState.isMisusePoint == false)
            {
                cm_m_mr.IsEnabled = false;
            }
            if (m_ref_s.isEmpty == false)
            {
                cm_m_mr.IsChecked = true;
            }
            cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
            cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
            cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_m_mr.FontSize = 10;
            //cm_m_act.Background = Brushes.OrangeRed;
            cm_m_mr.IsCheckable = true;

            cm.Items.Add(cm_i);
            cm.Items.Add(cm_i_e);
            //cm.Items.Add(cm_mp);
            cm.Items.Add(cm_mu);
            cm.Items.Add(cm_m_mr);

            tvi.ContextMenu = cm;

            states.Items.Add(tvi);

            newState = new State();
            newState.machineName = source_agent.assignedMachine.machineName;
            newState.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

            genStateMachineGraph(source_agent.agentName);
        }

        private void update_state_b_Click(object sender, RoutedEventArgs e)
        {

            if (newState == null)
            {
                return;
            }

            string stateName = new_ent_name_tb.Text;
            stateName = stateName.Trim();
            stateName = stateName.TrimEnd('\n');
            stateName = stateName.TrimEnd('\r');

            if (stateName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL state name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }


            if (isStateUpdate == false)
            {
                if (existingState(stateName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, stateName + " state already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }

            }

            newState.name = stateName;
            newState.machineName = source_agent.assignedMachine.machineName;
            string stateDesc = new_ent_desc_tb.Text;
            newState.description = stateDesc;

            if (isCallableState_cb.IsChecked == true)
            {
                newState.isCallable = true;
            }
            else
            {
                newState.isCallable = false;
            }

            MisUseAnObjectsDB.updateStateDB(newState, MainWindow.clusterName);

            loadStates();
            loadTransitions();

            newState = new State();
            newState.machineName = source_agent.assignedMachine.machineName;
            newState.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

            genStateMachineGraph(source_agent.agentName);
        }

        private void delete_state_b_Click(object sender, RoutedEventArgs e)
        {
            string stateName = new_ent_name_tb.Text;
            stateName = stateName.Trim();
            stateName = stateName.TrimEnd('\n');
            stateName = stateName.TrimEnd('\r');

            if (stateName.Count() > 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "confirm delete of " + stateName + " state",
                            "Confirm", MessageBoxButton.YesNo,
                            MessageBoxImage.Information);

                if (result == MessageBoxResult.No)
                {
                    return;
                }
                else
                {
                    MisUseAnObjectsDB.deleteStateDB(source_agent.assignedMachine.machineName, stateName, MainWindow.clusterName);
                    if (source_agent.assignedMachine != null)
                    {
                        source_agent.assignedMachine.removeState(stateName);
                    }

                    allExistingStates = MisUseAnObjectsDB.loadAllStates(source_agent.assignedMachine.machineName, MainWindow.clusterName);
                    newState = new State();
                    newState.machineName = source_agent.assignedMachine.machineName;
                    newState.clusterName = MainWindow.clusterName;
                    new_ent_name_tb.Text = "";
                    new_ent_desc_tb.Text = "";

                    new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                    desc_l.Visibility = System.Windows.Visibility.Hidden;
                    update_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                    update_state_b.Visibility = System.Windows.Visibility.Hidden;
                    define_state_b.Visibility = System.Windows.Visibility.Hidden;
                    operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                    state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                    transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                    update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    start_state_l.Visibility = System.Windows.Visibility.Hidden;
                    start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                    associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                    end_state_l.Visibility = System.Windows.Visibility.Hidden;
                    end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
                    isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

                    foreach (TreeViewItem item in states.Items)
                    {
                        if (item.Tag.Equals(stateName))
                        {
                            states.Items.Remove(item);
                            break;
                        }
                    }
                    loadTransitions();
                }
            }

            genStateMachineGraph(source_agent.agentName);
        }
        
        bool existingState(string stateName)
        {
            bool exist = false;

            if (allExistingStates == null)
            {
                allExistingStates = MisUseAnObjectsDB.loadAllStates(source_agent.assignedMachine.machineName, MainWindow.clusterName);
            }
            foreach (State eve in allExistingStates)
            {
                if (eve.name.Equals(stateName))
                {
                    exist = true;
                    break;
                }
            }
            return exist;
        }

        private void state_action_delete_b_Click(object sender, RoutedEventArgs e)
        {
            string actionName = new_ent_name_tb.Text;
            actionName = actionName.Trim();
            actionName = actionName.TrimEnd('\n');
            actionName = actionName.TrimEnd('\r');

            if (actionName.Count() > 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "confirm delete of " + actionName + " action",
                            "Confirm", MessageBoxButton.YesNo,
                            MessageBoxImage.Information);

                if (result == MessageBoxResult.No)
                {
                    return;
                }
                else
                {
                    MisUseAnObjectsDB.deleteStateActionDB(source_agent.assignedMachine.machineName, stateName_, actionName, MainWindow.clusterName);
                    if (newState != null)
                    {
                        newState.removeAction(actionName);
                    }

                    allExistingStateActions = MisUseAnObjectsDB.loadAllStateActions(source_agent.assignedMachine.machineName, stateName_, MainWindow.clusterName);
                    newAction = new PMisuseAn.behaviour.model.Action();
                    newAction.machineName = source_agent.assignedMachine.machineName;
                    newAction.clusterName = MainWindow.clusterName;
                    new_ent_name_tb.Text = "";
                    new_ent_desc_tb.Text = "";

                    new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                    desc_l.Visibility = System.Windows.Visibility.Hidden;
                    update_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                    update_state_b.Visibility = System.Windows.Visibility.Hidden;
                    define_state_b.Visibility = System.Windows.Visibility.Hidden;
                    operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                    state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                    transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                    update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    start_state_l.Visibility = System.Windows.Visibility.Hidden;
                    start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                    associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                    end_state_l.Visibility = System.Windows.Visibility.Hidden;
                    end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
                    isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

                    foreach (TreeViewItem item in stateActionSelected_tv.Items)
                    {
                        string tag_id = (string)item.Tag;
                        string[] tag_split = tag_id.Split(',');

                        string actname = tag_split[0];
                        string staname = tag_split[1];

                        if (actname.Equals(actionName))
                        {
                            stateActionSelected_tv.Items.Remove(item);
                            break;
                        }
                    }
                }
            }
        }

        private void state_action_update_b_Click(object sender, RoutedEventArgs e)
        {
            string actionName = new_ent_name_tb.Text;
            actionName = actionName.Trim();
            actionName = actionName.TrimEnd('\n');
            actionName = actionName.TrimEnd('\r');

            if (actionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "State action name required",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            if (isStateActionUpdate == false)
            {
                if (existingStateAction(stateName_, actionName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, actionName + " action already exist in associating state.",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }
            }

            if (newAction == null)
            {
                newAction = new PMisuseAn.behaviour.model.Action();
                newAction.clusterName = MainWindow.clusterName;
            }

            newAction.name = actionName;
            newAction.stateName = stateName_;
            newAction.machineName = source_agent.assignedMachine.machineName;
            string actionDesc = new_ent_desc_tb.Text;
            newAction.description = actionDesc;

            MisUseAnObjectsDB.updateStateActionDB(newAction, MainWindow.clusterName);

            TreeViewItem item_action = new TreeViewItem();
            item_action.Header = newAction.name;
            item_action.Tag = newAction.name + "," + stateName_;
            item_action.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));

            bool exist = false;
            foreach (TreeViewItem etv in stateActionSelected_tv.Items)
            {
                string tag_etv = (string)etv.Tag;
                if (tag_etv.Equals((string)item_action.Tag))
                {
                    exist = true;
                }
            }
            if (exist == false)
            {
                stateActionSelected_tv.Items.Add(item_action);
                stateActionSelected_tv.IsExpanded = true;
            }

            newAction = new PMisuseAn.behaviour.model.Action();
            newAction.machineName = source_agent.assignedMachine.machineName;
            newAction.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
        }

        private void state_action_apply_b_Click(object sender, RoutedEventArgs e)
        {
            string actionName = new_ent_name_tb.Text;
            actionName = actionName.Trim();
            actionName = actionName.TrimEnd('\n');
            actionName = actionName.TrimEnd('\r');

            if (actionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "State action name required",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }


            if (isStateActionUpdate == false)
            {
                if (existingStateAction(stateName_, actionName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, actionName + " action already exist in associating state.",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }
            }

            if (newAction == null)
            {
                newAction = new PMisuseAn.behaviour.model.Action();
                newAction.clusterName = MainWindow.clusterName;
            }

            newAction.name = actionName;
            newAction.stateName = stateName_;
            newAction.machineName = source_agent.assignedMachine.machineName;
            string actionDesc = new_ent_desc_tb.Text;
            newAction.description = actionDesc;

            MisUseAnObjectsDB.addStateActionDB(newAction, MainWindow.clusterName);

            TreeViewItem item_action = new TreeViewItem();
            item_action.Header = newAction.name;
            item_action.Tag = newAction.name + "," + stateName_;
            item_action.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));

            //if (newAction.isMitigationPoint == true)
            //{
            //    item_action.Background = Brushes.LightYellow;
            //}
            if (newAction.isMisusePoint == true)
            {
                item_action.Background = Brushes.OrangeRed;
            }
            MitigationReferences m_ref = MisUseAnObjectsDB.loadStateActionMitigationReferencesDB(newAction.name, stateName_, source_agent.assignedMachine.machineName, MainWindow.clusterName);

            if (m_ref.isEmpty == false)
            {
                item_action.Background = Brushes.Green;
            }
            ContextMenu cm_act = new System.Windows.Controls.ContextMenu();
            cm_act.Height = 60;
            cm_act.Width = 150;


            //MenuItem cm_mp_act = new MenuItem();
            //cm_mp_act.Header = "mitigation point";
            //cm_mp_act.Tag = newAction.name + "," + stateName_;
            //if (newAction.isMitigationPoint == true)
            //{
            //    cm_mp_act.IsChecked = true;
            //}
            //cm_mp_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_state_action_clicked));
            //cm_mp_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_state_action_clicked));
            //cm_mp_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            //cm_mp_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            //cm_mp_act.FontSize = 10;
            //cm_mp_act.Background = Brushes.LightYellow;
            //cm_mp_act.IsCheckable = true;

            MenuItem cm_mu_act = new MenuItem();
            cm_mu_act.Header = "misuse point";
            cm_mu_act.Tag = newAction.name + "," + stateName_;
            if (newAction.isMisusePoint == true)
            {
                cm_mu_act.IsChecked = true;
            }
            cm_mu_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
            cm_mu_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
            cm_mu_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_mu_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_mu_act.FontSize = 10;
            //cm_mu_act.Background = Brushes.OrangeRed;
            cm_mu_act.IsCheckable = true;

            MenuItem cm_m_act = new MenuItem();
            cm_m_act.Header = "Mitigation references";
            cm_m_act.Tag = newAction.name + "," + stateName_;
            if (newAction.isMisusePoint == false)
            {
                cm_m_act.IsEnabled = false;
            }
            if (m_ref.isEmpty == false)
            {
                cm_m_act.IsChecked = true;
            }
            cm_m_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
            cm_m_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
            cm_m_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_m_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_m_act.FontSize = 10;
            //cm_m_act.Background = Brushes.OrangeRed;
            cm_m_act.IsCheckable = true;

            //cm_act.Items.Add(cm_mp_act);
            cm_act.Items.Add(cm_mu_act);
            cm_act.Items.Add(cm_m_act);

            item_action.ContextMenu = cm_act;

            bool exist = false;
            foreach (TreeViewItem etv in stateActionSelected_tv.Items)
            {
                string tag_etv = (string)etv.Tag;
                if (tag_etv.Equals((string)item_action.Tag))
                {
                    exist = true;
                }
            }
            if (exist == false)
            {
                stateActionSelected_tv.Items.Add(item_action);
                stateActionSelected_tv.IsExpanded = true;
            }

            newAction = new PMisuseAn.behaviour.model.Action();
            newAction.machineName = source_agent.assignedMachine.machineName;
            newAction.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
        }

        private void apply_new_state_transition_b_Click(object sender, RoutedEventArgs e)
        {
            string transitionName = new_ent_name_tb.Text;
            transitionName = transitionName.Trim();
            transitionName = transitionName.TrimEnd('\n');
            transitionName = transitionName.TrimEnd('\r');

            string startState = start_state_cb.Text;
            string endState = end_state_cb.Text;
            string associatedEvent = associated_event_cb.Text;

            if (transitionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "Transition name field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (startState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "start state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (endState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "end state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (associatedEvent.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "associated event field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            //if (existingStateTransition(transitionName, startState, endState, associatedEvent))
            if (existingStateTransition(transitionName))
            {
                MessageBoxResult result = MessageBox.Show(this, transitionName + " already exist",
                                            "error", MessageBoxButton.OK,
                                            MessageBoxImage.Information);
                return;
            }

            if (newStateTransition == null)
            {
                newStateTransition = new Transition();
                newStateTransition.machineName = source_agent.assignedMachine.machineName;
                newStateTransition.clusterName = MainWindow.clusterName;
            }
            newStateTransition.transitionName = transitionName;
            newStateTransition.startState = startState;
            newStateTransition.endState = endState;
            newStateTransition.associatedEevent = associatedEvent;

            if (isCallableTransition_cb.IsChecked == true)
            {
                newStateTransition.isCallable = true;
            }
            else
            {
                newStateTransition.isCallable = false;
            }
            MisUseAnObjectsDB.addStateTransitionDB(newStateTransition, MainWindow.clusterName);

            string trans_tag = newStateTransition.transitionName + "," + newStateTransition.machineName + "," + newStateTransition.startState +
                    "," + newStateTransition.endState + "," + newStateTransition.associatedEevent;
            string trans_content = newStateTransition.transitionName + "(" + newStateTransition.startState +
                "," + newStateTransition.endState + "," + newStateTransition.associatedEevent + ")";
            if (!transitions.Items.Contains(trans_content))
            {
                TreeViewItem item = new TreeViewItem();
                item.Header = trans_content;
                item.Tag = trans_tag;
                item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));

                //if (newStateTransition.isMitigationPoint == true)
                //{
                //    item.Background = Brushes.LightYellow;
                //}
                if (newStateTransition.isMisusePoint == true)
                {
                    item.Background = Brushes.OrangeRed;
                }

                MitigationReferences m_ref_s = MisUseAnObjectsDB.loadTransitionMitigationReferencesDB(newStateTransition.transitionName, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                if (m_ref_s.isEmpty == false)
                {
                    item.Background = Brushes.Green;
                }

                ContextMenu cm_trans = new System.Windows.Controls.ContextMenu();
                cm_trans.Height = 60;
                cm_trans.Width = 150;

                //MenuItem cm_mp_trans = new MenuItem();
                //cm_mp_trans.Header = "mitigation point";
                //cm_mp_trans.Tag = trans_tag;
                //if (newStateTransition.isMitigationPoint == true)
                //{
                //    cm_mp_trans.IsChecked = true;
                //}
                //cm_mp_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                //cm_mp_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                //cm_mp_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                //cm_mp_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                //cm_mp_trans.FontSize = 10;
                //cm_mp_trans.Background = Brushes.LightYellow;
                //cm_mp_trans.IsCheckable = true;

                MenuItem cm_mu_trans = new MenuItem();
                cm_mu_trans.Header = "misuse point";
                cm_mu_trans.Tag = trans_tag;
                if (newStateTransition.isMisusePoint == true)
                {
                    cm_mu_trans.IsChecked = true;
                }
                cm_mu_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                cm_mu_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                cm_mu_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                cm_mu_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                cm_mu_trans.FontSize = 10;
                //cm_mu_trans.Background = Brushes.OrangeRed;
                cm_mu_trans.IsCheckable = true;

                MenuItem cm_m_mr = new MenuItem();
                cm_m_mr.Header = "Mitigation references";
                cm_m_mr.Tag = trans_tag;

                if (newStateTransition.isMisusePoint == false)
                {
                    cm_m_mr.IsEnabled = false;
                }
                if (m_ref_s.isEmpty == false)
                {
                    cm_m_mr.IsChecked = true;
                }
                cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                cm_m_mr.FontSize = 10;
                //cm_m_act.Background = Brushes.OrangeRed;
                cm_m_mr.IsCheckable = true;

                //cm_trans.Items.Add(cm_mp_trans);
                cm_trans.Items.Add(cm_mu_trans);
                cm_trans.Items.Add(cm_m_mr);

                item.ContextMenu = cm_trans;
                transitions.Items.Add(item);
            }

            newStateTransition = new Transition();
            newStateTransition.machineName = source_agent.assignedMachine.machineName;
            newStateTransition.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            start_state_cb.Text = "";
            end_state_cb.Text = "";
            associated_event_cb.Text = "";
            loadStateTransitionsPolicyStatementList();

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

            genStateMachineGraph(source_agent.agentName);
        }

        private void update_new_state_transition_b_Click(object sender, RoutedEventArgs e)
        {
            string transitionName = new_ent_name_tb.Text;
            transitionName = transitionName.Trim();
            transitionName = transitionName.TrimEnd('\n');
            transitionName = transitionName.TrimEnd('\r');

            string startState = start_state_cb.Text;
            string endState = end_state_cb.Text;
            string associatedEvent = associated_event_cb.Text;

            if (transitionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "Transition name field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (startState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "start state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (endState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "end state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (associatedEvent.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "associated event field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            ////if (existingStateTransition(transitionName, startState, endState, associatedEvent))
            //if (existingStateTransition(transitionName))
            //{
            //    MessageBoxResult result = MessageBox.Show(this, transitionName + " already exist",
            //                                "error", MessageBoxButton.OK,
            //                                MessageBoxImage.Information);
            //    return;
            //}

            if (newStateTransition == null)
            {
                return;
            }
            string trans_content_old = newStateTransition.transitionName + "(" + newStateTransition.startState +
                "," + newStateTransition.endState + "," + newStateTransition.associatedEevent + ")";
            string trans_tag_old = newStateTransition.transitionName + "," + newStateTransition.machineName + "," + newStateTransition.startState +
                    "," + newStateTransition.endState + "," + newStateTransition.associatedEevent;

            foreach (TreeViewItem item in transitions.Items)
            {
                string tagx = (string)item.Tag;
                if (tagx.Equals(trans_tag_old))
                {
                    transitions.Items.Remove(item);
                    break;
                }
            }

            newStateTransition.transitionName = transitionName;
            newStateTransition.startState = startState;
            newStateTransition.endState = endState;
            newStateTransition.associatedEevent = associatedEvent;

            if (isCallableTransition_cb.IsChecked == true)
            {
                newStateTransition.isCallable = true;
            }
            else
            {
                newStateTransition.isCallable = false;
            }
            MisUseAnObjectsDB.updateStateTransitionDB(newStateTransition, MainWindow.clusterName);

            string trans_tag = newStateTransition.transitionName + "," + newStateTransition.machineName + "," + newStateTransition.startState +
                    "," + newStateTransition.endState + "," + newStateTransition.associatedEevent;
            string trans_content = newStateTransition.transitionName + "(" + newStateTransition.startState +
                "," + newStateTransition.endState + "," + newStateTransition.associatedEevent + ")";
            if (!transitions.Items.Contains(trans_content))
            {
                TreeViewItem item = new TreeViewItem();
                item.Header = trans_content;
                item.Tag = trans_tag;
                item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));

                //if (newStateTransition.isMitigationPoint == true)
                //{
                //    item.Background = Brushes.LightYellow;
                //}
                if (newStateTransition.isMisusePoint == true)
                {
                    item.Background = Brushes.OrangeRed;
                }

                MitigationReferences m_ref_s = MisUseAnObjectsDB.loadTransitionMitigationReferencesDB(newStateTransition.transitionName, source_agent.assignedMachine.machineName, MainWindow.clusterName);

                if (m_ref_s.isEmpty == false)
                {
                    item.Background = Brushes.Green;
                }

                ContextMenu cm_trans = new System.Windows.Controls.ContextMenu();
                cm_trans.Height = 60;
                cm_trans.Width = 150;

                //MenuItem cm_mp_trans = new MenuItem();
                //cm_mp_trans.Header = "mitigation point";
                //cm_mp_trans.Tag = trans_tag;
                //if (newStateTransition.isMitigationPoint == true)
                //{
                //    cm_mp_trans.IsChecked = true;
                //}
                //cm_mp_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                //cm_mp_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                //cm_mp_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                //cm_mp_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                //cm_mp_trans.FontSize = 10;
                //cm_mp_trans.Background = Brushes.LightYellow;
                //cm_mp_trans.IsCheckable = true;

                MenuItem cm_mu_trans = new MenuItem();
                cm_mu_trans.Header = "misuse point";
                cm_mu_trans.Tag = trans_tag;
                if (newStateTransition.isMisusePoint == true)
                {
                    cm_mu_trans.IsChecked = true;
                }
                cm_mu_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                cm_mu_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                cm_mu_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                cm_mu_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                cm_mu_trans.FontSize = 10;
                //cm_mu_trans.Background = Brushes.OrangeRed;
                cm_mu_trans.IsCheckable = true;

                MenuItem cm_m_mr = new MenuItem();
                cm_m_mr.Header = "Mitigation references";
                cm_m_mr.Tag = trans_tag;

                if (newStateTransition.isMisusePoint == false)
                {
                    cm_m_mr.IsEnabled = false;
                }
                if (m_ref_s.isEmpty == false)
                {
                    cm_m_mr.IsChecked = true;
                }
                cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                cm_m_mr.FontSize = 10;
                //cm_m_act.Background = Brushes.OrangeRed;
                cm_m_mr.IsCheckable = true;

                //cm_trans.Items.Add(cm_mp_trans);
                cm_trans.Items.Add(cm_mu_trans);
                cm_trans.Items.Add(cm_m_mr);

                item.ContextMenu = cm_trans;
                transitions.Items.Add(item);
            }

            newStateTransition = new Transition();
            newStateTransition.machineName = source_agent.assignedMachine.machineName;
            newStateTransition.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            start_state_cb.Text = "";
            end_state_cb.Text = "";
            associated_event_cb.Text = "";
            loadStateTransitionsPolicyStatementList();

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

            genStateMachineGraph(source_agent.agentName);
        }

        private void delete_state_transition_b_Click(object sender, RoutedEventArgs e)
        {
            string transitionName = new_ent_name_tb.Text;
            transitionName = transitionName.Trim();
            transitionName = transitionName.TrimEnd('\n');
            transitionName = transitionName.TrimEnd('\r');

            string startState = start_state_cb.Text;
            string endState = end_state_cb.Text;
            string associatedEvent = associated_event_cb.Text;

            if (transitionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "Transition name field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (startState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "start state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (endState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "end state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (associatedEvent.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "associated event field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            if (newStateTransition == null)
            {
                newStateTransition = new Transition();
                newStateTransition.machineName = source_agent.assignedMachine.machineName;
                newStateTransition.clusterName = MainWindow.clusterName;
            }
            newStateTransition.transitionName = transitionName;
            newStateTransition.startState = startState;
            newStateTransition.endState = endState;
            newStateTransition.associatedEevent = associatedEvent;

            MessageBoxResult result1 = MessageBox.Show(this, transitionName + " transition will be deleted permanently!",
                            "Confirm", MessageBoxButton.YesNo,
                            MessageBoxImage.Information);

            if (result1 == MessageBoxResult.No)
            {
                return;
            }
            else
            {
                MisUseAnObjectsDB.deleteStateTransitionDBTransStateEvent(newStateTransition, MainWindow.clusterName);
                if (source_agent.assignedMachine != null)
                {
                    source_agent.assignedMachine.removeStateTransition(newStateTransition.transitionName);
                }

                allExistingStateTransitions = MisUseAnObjectsDB.loadAllStateTransitions(source_agent.assignedMachine.machineName, MainWindow.clusterName);
                newStateTransition = new Transition();
                newStateTransition.machineName = source_agent.assignedMachine.machineName;
                newStateTransition.clusterName = MainWindow.clusterName;

                new_ent_name_tb.Text = "";
                new_ent_name_tb.IsReadOnly = false;
                start_state_cb.Text = "";
                start_state_cb.IsEnabled = true;
                end_state_cb.Text = "";
                end_state_cb.IsEnabled = true;
                associated_event_cb.Text = "";
                associated_event_cb.IsEnabled = true;
                loadStateTransitionsPolicyStatementList();

                new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
                new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
                apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
                new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                desc_l.Visibility = System.Windows.Visibility.Hidden;
                update_event_b.Visibility = System.Windows.Visibility.Hidden;
                delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                update_state_b.Visibility = System.Windows.Visibility.Hidden;
                define_state_b.Visibility = System.Windows.Visibility.Hidden;
                operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                start_state_l.Visibility = System.Windows.Visibility.Hidden;
                start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                end_state_l.Visibility = System.Windows.Visibility.Hidden;
                end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
                isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

                foreach (TreeViewItem item in transitions.Items)
                {
                    string tag_id = (string)item.Tag;
                    if (!tag_id.Equals("new"))
                    {
                        string[] tag_comps = tag_id.Split(',');
                        string transitionName_t = tag_comps[0];
                        string machineName_t = tag_comps[1];
                        string startState_t = tag_comps[2];
                        string endState_t = tag_comps[3];
                        string associatedEvent_t = tag_comps[4];

                        if (transitionName_t.Equals(transitionName)
                            && machineName_t.Equals(source_agent.assignedMachine.machineName)
                            && startState_t.Equals(startState)
                            && endState_t.Equals(endState)
                            && associatedEvent_t.Equals(associatedEvent))
                        {
                            transitions.Items.Remove(item);
                            break;
                        }
                    }
                }
            }

            genStateMachineGraph(source_agent.agentName);
        }
        
        bool existingStateTransition(string transitionName)
        {
            bool exist = false;

            if (allExistingStateTransitions == null)
            {
                allExistingStateTransitions = MisUseAnObjectsDB.loadAllStateTransitions(source_agent.assignedMachine.machineName, MainWindow.clusterName);
            }
            foreach (Transition eve in allExistingStateTransitions)
            {
                if (eve.machineName.Equals(source_agent.assignedMachine.machineName)
                        && eve.transitionName.Equals(transitionName))
                {
                    exist = true;
                    break;
                }
            }
            return exist;
        }

        //knowledge evolution tab
        public void loadDomainAttributes()
        {
            List<Attribute> attributes = MisUseAnObjectsDB.loadAllAttributes(MainWindow.clusterName);
            attributes_lb.Items.Clear();

            int att_no = 1;
            foreach (Attribute att in attributes)
            {
                ListBoxItem l = new ListBoxItem();
                StackPanel s = new StackPanel();
                s.Orientation = System.Windows.Controls.Orientation.Horizontal;

                ContentPresenter c1 = new ContentPresenter();
                c1.Content = att_no;
                att_no = att_no + 1;

                ContentPresenter c2 = new ContentPresenter();

                Button open_att_b = new Button();
                open_att_b.Tag = att;
                open_att_b.Style = (System.Windows.Style)FindResource("LinkButton");
                open_att_b.Height = 15;
                open_att_b.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                open_att_b.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                open_att_b.Content = att.name;


                //open_att_b.AddHandler(Button.ClickEvent, new RoutedEventHandler(open_att_b_Click));
                open_att_b.Dispatcher.Invoke(new System.Action(() => open_att_b.AddHandler(Button.ClickEvent, new RoutedEventHandler(open_att_b_Click))), DispatcherPriority.Normal, null);                               
                c2.Content = open_att_b;

                if (attributes_lb.Items.Count % 2 == 0)
                {
                    l.Background = Brushes.AliceBlue;
                }

                c1.Width = 15;
                c2.Width = attributes_lb.Width - 40;
                s.Children.Add(c1);
                s.Children.Add(c2);

                //add context menu to item to clone state machine
                //use cloneStateMachineDB method in DB class

                ContextMenu cm = new System.Windows.Controls.ContextMenu();
                cm.Height = 64;
                cm.Width = 205;

                MenuItem cm_d = new MenuItem();
                cm_d.Header = "Delete                     ";
                cm_d.Tag = att;
                cm_d.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(del_att_Click));
                cm_d.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                cm_d.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                cm_d.FontSize = 12;
                cm_d.Foreground = Brushes.DarkGreen;

                BitmapImage cm_d_image = new BitmapImage();
                cm_d_image.BeginInit();
                Uri cm_d_Uri = new Uri("/PMisuseAn;component/images/DeleteHS.png", UriKind.RelativeOrAbsolute);
                cm_d_image.UriSource = cm_d_Uri;
                cm_d_image.EndInit();
                
                cm.Items.Add(cm_d);
                l.ContextMenu = cm;

                l.Content = s;
                l.Tag = att;

                attributes_lb.Items.Add(l);
            }
        }

        private void loadExistingPolicies()
        {
            List<Policy> policy_statements = MisUseAnObjectsDB.loadAllPolicyStatementsFull(MainWindow.clusterName);

            if (policy_statements != null)
            {
                policies_lb.Items.Clear();
                int pol_no = 1;

                foreach (Policy policy in policy_statements)
                {
                    ListBoxItem l = new ListBoxItem();
                    l.FontSize = 10.5;
                    StackPanel s = new StackPanel();
                    s.Orientation = System.Windows.Controls.Orientation.Horizontal;

                    ContentPresenter c1 = new ContentPresenter();
                    c1.Content = pol_no + ".";
                    pol_no = pol_no + 1;

                    ContentPresenter c2 = new ContentPresenter();
                    c2.Content = " [TP:" + policy.transmissionPrinciple + "]";

                    ContentPresenter c3 = new ContentPresenter();

                    if (!policy.statement.Equals("DO[NILL]"))
                    {
                        ListBox lb2 = new ListBox();
                        lb2.FontSize = 10.5;

                        PolicyStatementAnalyser psa = new PolicyStatementAnalyser();
                        psa.ifThenUnlessTokenisation(policy.statement);

                        ListBoxItem lb2l1 = new ListBoxItem();
                        string if_content = "IF" + psa.if_content;
                        lb2l1.Content = if_content;
                        lb2.Items.Add(lb2l1);
                        ListBoxItem lb2l2 = new ListBoxItem();
                        string then_content = "   THEN" + psa.then_content;
                        lb2l2.Content = then_content;
                        lb2.Items.Add(lb2l2);
                        if (psa.unless_content != null)
                        {
                            ListBoxItem lb2l3 = new ListBoxItem();
                            string unless_content = "   UNLESS" + psa.unless_content;
                            lb2l3.Content = unless_content;
                            lb2.Items.Add(lb2l3);
                        }

                        if (policies_lb.Items.Count % 2 == 0)
                        {
                            l.Background = Brushes.AliceBlue;

                            lb2.Background = Brushes.AliceBlue;
                            lb2.BorderBrush = Brushes.AliceBlue;
                        }
                        else
                        {
                            lb2.BorderBrush = Brushes.White;
                        }
                        c3.Content = lb2;
                    }
                    else
                    {
                        c3.Content = policy.statement;
                        if (policies_lb.Items.Count % 2 == 0)
                        {
                            l.Background = Brushes.AliceBlue;
                            l.Foreground = Brushes.DarkRed;
                        }
                    }

                    c1.Width = 15;
                    c2.Width = 98;
                    c3.Width = policies_lb.Width - 140;
                    s.Children.Add(c1);
                    s.Children.Add(c2);
                    s.Children.Add(c3);

                    //add context menu to item to clone state machine
                    //use cloneStateMachineDB method in DB class

                    ContextMenu cm = new System.Windows.Controls.ContextMenu();
                    cm.Height = 64;
                    cm.Width = 136;

                    MenuItem cm_d = new MenuItem();
                    cm_d.Header = "Delete";
                    cm_d.Tag = policy;
                    cm_d.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(del_policy_statement_b_Click));
                    cm_d.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_d.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_d.FontSize = 12;
                    cm_d.Foreground = Brushes.DarkGreen;

                    BitmapImage cm_d_image = new BitmapImage();
                    cm_d_image.BeginInit();
                    Uri cm_d_Uri = new Uri("/PMisuseAn;component/images/DeleteHS.png", UriKind.RelativeOrAbsolute);
                    cm_d_image.UriSource = cm_d_Uri;
                    cm_d_image.EndInit();

                    Image cm_d_iconImage = new Image();
                    cm_d_iconImage.Source = cm_d_image;
                    cm_d.Icon = cm_d_iconImage;

                    cm.Items.Add(cm_d);
                    l.ContextMenu = cm;

                    l.Content = s;
                    l.Tag = policy;

                    policies_lb.Items.Add(l);
                }
            }
        }

        void del_policy_statement_b_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Confirm delete...", "Delete", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.No)
            {
                return;
            }
            MenuItem d_b = (MenuItem)sender;
            Policy tag_id = (Policy)d_b.Tag;

            MisUseAnObjectsDB.deletePolicyStatement(tag_id.statement, tag_id.transmissionPrinciple, MainWindow.clusterName);
            loadExistingPolicies();
        }

        public void new_policy_b_Click(object sender, RoutedEventArgs e)
        {
            AddPolicyWindow1 apw = new AddPolicyWindow1();
            apw.Owner = (Window)this.Parent;
            apw.ShowDialog();
            loadExistingPolicies();
        }

        public void new_aggregationrule_b_Click(object sender, RoutedEventArgs e)
        {
            AddAggregateFromToAttributeWindow1 aaftaw = new AddAggregateFromToAttributeWindow1();
            aaftaw.Owner = (Window)this.Parent;
            aaftaw.ShowDialog();
            loadDomainAttributes();
        }

        public void configAdaptationMgr_Click(object sender, RoutedEventArgs e)
        {
            AdaptationMgtConfigWindow amcw = new AdaptationMgtConfigWindow();
            amcw.Owner = (Window)this.Parent;
            amcw.ShowDialog();
        }

        public void threatHistory_b_Click(object sender, RoutedEventArgs e)
        {
            if (source_agent_name != null)
            {
                ThreatMitigationHistoryWindow amcw = new ThreatMitigationHistoryWindow(source_agent_name);
                amcw.Owner = (Window)this.Parent;
                amcw.ShowDialog();
            }
        }
        

        public void del_att_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Confirm delete...", "Delete", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.No)
            {
                return;
            }

            MenuItem d_b = (MenuItem)sender;
            Attribute tag_id = (Attribute)d_b.Tag;
            MisUseAnObjectsDB.deleteAttribute(tag_id, MainWindow.clusterName);

            loadDomainAttributes();
        }

        public void open_att_b_Click(object sender, RoutedEventArgs e)
        {
            Button a_b = (Button)sender;
            Attribute att = (Attribute)a_b.Tag;
            Attribute full_att = MisUseAnObjectsDB.loadAttributeFull(att.name, MainWindow.clusterName);
            AddActorAttributeWindow acw = new AddActorAttributeWindow(this, full_att);
            acw.Owner = (Window)this.Parent;
            acw.ShowDialog();
        }

        private void add_att_b_Click(object sender, RoutedEventArgs e)
        {
            AddActorAttributeWindow acw = new AddActorAttributeWindow(this);
            acw.Owner = (Window)this.Parent;
            acw.ShowDialog();
        }

        private void refresh_att_Button_Click(object sender, RoutedEventArgs e)
        {
            loadDomainAttributes();
        }

        public RoutedEventHandler threatHistoryItemSelected { get; set; }

    }
}
